40. Combination Sum II

2018/10/03 leetcode 共 1363 字,约 4 分钟

title

problem link

Given a collection of candidate numbers (candidates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target.

Each number in candidates may only be used once in the combination.

Note:

All numbers (including target) will be positive integers.

The solution set must not contain duplicate combinations.

Example 1:

Input: candidates = [10,1,2,7,6,1,5], target = 8,

A solution set is: [ [1, 7], [1, 2, 5], [2, 6], [1, 1, 6] ]

Example 2:

Input: candidates = [2,5,2,1,2], target = 5,

A solution set is:

[
  [1,2,2],
  [5]
]

solution

class Solution {
public:
	void backtracking(vector<vector<int>> &res, vector<int>& t,vector<int>& can,vector<bool> &visit, int target, int start) {
		if (target == 0) {
			res.push_back(t);
			return;
		}
		if (target < 0 || start == can.size()) 
			return;
		for (int i = start; i < can.size(); i++) {
			if (i != 0 && can[i] == can[i - 1] && !visit[i - 1]) {
				continue;
			}
			visit[i] = true;
			t.push_back(can[i]);
			backtracking(res, t, can, visit, target - can[i], i + 1);
			t.pop_back();
			visit[i] = false;
		}
	}
	vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
		vector<vector<int>> res;
		if (candidates.size() == 0) return res;
		vector<bool> visit(candidates.size());
		vector<int> t;
		sort(candidates.begin(), candidates.end());
		backtracking(res, t, candidates, visit, target, 0);
		return res;
	}
};

Search

    Table of Contents