LeetCode 40. Combination Sum II

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]
]
解析:
此题目与Leetcode 39. Combination Sum类似,只不过前一个题目允许重复使用元素,这个题目不能重复使用候选元素。在前一个题目基础之上调整一下即可。
首先在递归调用时,下标换成index+1,可以防止重复使用数组中的数字。
在递归循环中增加判断条件:if(i > start && candidates[i] == candidates[i-1]) continue 排序之后对于重复元素后面的不再处理,避免res中出现重复项。

class Solution {
public:
    vector<vector<int>>res;
    vector<int>ans;
    int nums_len;

    vector<vector<int> > combinationSum2(vector<int> &candidates, int target) {
        if(candidates.empty()) 
            return res;
        nums_len = candidates.size();
        sort(candidates.begin(), candidates.end());
        dfs(0, 0, target, candidates);
        return res;
    }

    void dfs(int start, int sum, int target,vector<int> candidates){
        if(sum == target) 
        {
            res.push_back(ans); 
            return; 
        }
        else if(sum > target)
            return;
        else{
            for(int i = start; i < nums_len; i++){
                if(i > start && candidates[i] == candidates[i-1])
                    continue;
                ans.push_back(candidates[i]);
                dfs(i+1, sum + candidates[i], target, candidates);
                ans.pop_back();
            }
        }
    }
};

Add a Comment

邮箱地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据