40. Combination Sum II

Bertha 。 2022-04-12 09:17 294阅读 0赞

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:

  1. Input: candidates =
  2. [10,1,2,7,6,1,5], target = 8,
  3. A solution set is:
  4. [
  5. [1, 7],
  6. [1, 2, 5],
  7. [2, 6],
  8. [1, 1, 6]
  9. ]

Example 2:

  1. Input: candidates = [2,5,2,1,2], target = 5,
  2. A solution set is:
  3. [
  4. [1,2,2],
  5. [5]
  6. ]

方法:回溯法

要点:(1)排序(2)去重(3)剪枝。

  1. class Solution {
  2. public:
  3. vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
  4. vector<vector<int>> result; //存储最终结果
  5. vector<int> item; //回溯时,产生各个子集的数组
  6. set<vector<int>> setRes; //去重使用的集合
  7. sort(candidates.begin(), candidates.end()); //排序
  8. generate(0, candidates, item, setRes, result, 0, target);
  9. return result;
  10. }
  11. private:
  12. void generate(int i,vector<int>& candidates, vector<int>& item, set<vector<int>> &setRes, vector<vector<int>> &result, int sum,int target)
  13. {
  14. if(i>= candidates.size() || sum > target) //当元素已遍历完或者sum已经超过target
  15. return;
  16. sum += candidates[i];
  17. item.push_back(candidates[i]); //添加当前元素
  18. if(sum == target && setRes.find(item) == setRes.end()) //在setRes中无法找到item
  19. {
  20. setRes.insert(item);
  21. result.push_back(item);
  22. }
  23. generate(i+1, candidates,item,setRes,result,sum,target); //第一次递归调用
  24. sum -= candidates[i];
  25. item.pop_back(); //不添加当前元素
  26. generate(i+1, candidates,item,setRes,result,sum,target); //第二次递归调用
  27. }
  28. };

发表评论

表情:
评论列表 (有 0 条评论,294人围观)

还没有评论,来说两句吧...

相关阅读