Combination Sum II(LetCode)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u014485485/article/details/80956935

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]
]

给定一个都是正数的数组,元素可能有重复,让你找出所有和等于给定数的数组。

思路:递归、深度优先搜索、回溯

重复的数可以使用但不能给出重复的组合,需要加一个判断条件

class Solution {
public:
	vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
		vector<vector<int> > ans;
		vector<int> cur;
		sort(candidates.begin(), candidates.end());
		dfs(candidates, target, 0, ans, cur);
		return ans;
	}
	void dfs(vector<int>& candidates, int target, int start, vector<vector<int> >& ans, vector<int>& cur) {
		if (target < 0) return;//加速计算
		if (target == 0) {
			ans.push_back(cur);
			return;//加速计算,找到一种情况,后面都不可能满足了
		}
		
		for (int i = start; i < candidates.size(); i++) {
			if (i > start && candidates[i] == candidates[i - 1]) continue;//在一次查找下,重复数字不再使用,以便去掉重复组合
			cur.push_back(candidates[i]);
			dfs(candidates, target - candidates[i], i + 1, ans, cur);//这里从i+1 开始,而不是start+1,会有重复
			cur.pop_back();
		}
	}
};


猜你喜欢

转载自blog.csdn.net/u014485485/article/details/80956935