40. Combination Sum II(Leetcode每日一题-2020.09.10)

Problem

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.

Example1

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

Example2

Input: candidates = [2,5,2,1,2], target = 5,
A solution set is:
[
[1,2,2],
[5]
]

Solution

在39题的基础上,排序去重

class Solution {
     
public:
    vector<vector<int>> ret;
    vector<int> cand;

    vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
     

        cand = candidates;
        vector<int> comb;
        sort(cand.begin(),cand.end());
        dfs(comb,0,target);

        return ret;
    }

    void dfs(vector<int> &comb,int start,int target)
    {
     
        if(target < 0)
            return;
        if(target == 0)
        {
     
            ret.push_back(comb);
            return;
        }

        for(int i = start;i<cand.size();++i)
        {
     
            if(i > start && cand[i] == cand[i-1])
                continue;
            
            comb.push_back(cand[i]);
            
            dfs(comb,i+1,target-cand[i]);
            
            comb.pop_back();
        }
    }
};

你可能感兴趣的:(leetcode回溯)