LeetCode40. Combination Sum II(C++)

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>>result;
    vector<int>num,tempresult;
    int len;
    vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
        sort(candidates.begin(),candidates.end());
        num=candidates;
        len=num.size();
        dfs(target,0,0);
        return result;
    }
    void dfs(int target,int temp,int index){
        if(target<temp)
            return;
        if(temp==target){
            result.push_back(tempresult);
            return;
        }
        for(int i=index;i<len;i++){
            temp+=num[i];tempresult.push_back(num[i]);
            dfs(target,temp,i+1);
            temp-=num[i];tempresult.pop_back();
            int x=num[i];
            while(i<len-1&&num[i+1]==x)
                i++;
        } 
    }
};

猜你喜欢

转载自blog.csdn.net/qq_41562704/article/details/86489998