题目描述

给定一个数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。
candidates 中的每个数字在每个组合中只能使用一次。

说明:

  • 所有数字(包括目标数)都是正整数。
  • 解集不能包含重复的组合。

示例1

  1. 输入: candidates = [10,1,2,7,6,1,5], target = 8,
  2. 所求解集为:
  3. [
  4. [1, 7],
  5. [1, 2, 5],
  6. [2, 6],
  7. [1, 1, 6]
  8. ]

示例2

  1. 输入: candidates = [2,5,2,1,2], target = 5,
  2. 所求解集为:
  3. [
  4. [1,2,2],
  5. [5]
  6. ]

解题思路

先对原数组排序,仍然是采用回溯的方法,但这里需要注意由于存在重复的元素,因此我们需要在每次递归的时候用一个set记录是否访问过相同的元素:

  1. class Solution {
  2. public:
  3. vector<vector<int>> res;
  4. void func(vector<int>& candidates, vector<int> &curr, int idx, int target) {
  5. set<int> visited;
  6. for (int i=idx; i<candidates.size(); i++) {
  7. if (visited.count(candidates[i]))
  8. continue;
  9. visited.insert(candidates[i]);
  10. curr.push_back(candidates[i]);
  11. if (candidates[i] == target) {
  12. res.push_back(curr);
  13. curr.pop_back();
  14. return;
  15. }
  16. else {
  17. if (candidates[i] < target) {
  18. func(candidates, curr, i+1, target-candidates[i]);
  19. }
  20. else {
  21. curr.pop_back();
  22. return;
  23. }
  24. }
  25. curr.pop_back();
  26. }
  27. }
  28. vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
  29. sort(candidates.begin(), candidates.end());
  30. vector<int> curr;
  31. func(candidates, curr, 0, target);
  32. return res;
  33. }
  34. };