description:

给定target, 求给定数列中找到几个数(其中的数不可以重复使用,且一组数有几个也不做限制)的和为target,和上面那个题一毛一样的,就改一下下标就行了,背下来背下来背下来~~~
Note:

All numbers (including target) will be positive integers.
The solution set must not contain duplicate combinations. //这个条件注意了,只要是两个挨着的一样,那么就会导致最后出现相同的组合

Example:

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

answer:

class Solution {
public:
    vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
        vector<vector<int>> res;
        vector<int> out;
        sort(candidates.begin(), candidates.end()); //这里刚开始就没写,一定要先变成有序数组!!!
        combinationDFS(candidates, res, out, target, 0);
        return res;
    }
    void combinationDFS(vector<int>& candidates, vector<vector<int>>& res, vector<int>& out, int target, int start) {
        if(target < 0) return;
        if(target == 0) {
            res.push_back(out);
            return;
        }
        for(int i = start; i < candidates.size(); i++) {
            if(i > start && candidates[i] == candidates[i - 1]) continue; //这里也要注意了,因为上边那个note的第二条
            out.push_back(candidates[i]);
            combinationDFS(candidates, res, out, target - candidates[i], i + 1);
            out.pop_back();
        }
    }
};

relative point get√:

hint :