LeetCode 40:组合总和 II(Combination Sum II)解法汇总

文章目录

  • Solution

更多LeetCode题解

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

Solution

此题与第39题唯一的区别是该题不允许重复使用元素,因此只需在第39题代码的基础上稍加修改就可以了(每次搜索的位置不是从头开始,而要去除已搜过的位置)

class Solution {
public:
    vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
        vector<vector<int>> solutionSet;
        for(int i=0;i<candidates.size();i++) {
            vector<int> res;
            res.push_back(candidates[i]);
            int count = i+1;
            findSolution(solutionSet, target-candidates[i], res, candidates, count);
        }
        return solutionSet;
    }
    void findSolution(vector<vector<int>>& solutionSet, int target, vector<int>& res, vector<int>& candidates,int count){
        if(target==0){
            vector<int> c_res=res;//res后面要擦除一位,不能直接sort res。
            sort(c_res.begin(),c_res.end());
            if(find(solutionSet.begin(),solutionSet.end(), c_res) == solutionSet.end()){
                solutionSet.push_back(c_res);
            }
            res.erase(res.end()-1);
            return;
        }
        else if(target>0){
            for(int i =count;i<candidates.size();i++){
                res.push_back(candidates[i]);
                count = i+1;
                findSolution(solutionSet, target-candidates[i], res, candidates, count);
            }
            res.erase(res.end()-1);
            return;
        }
        else{
            res.erase(res.end()-1);
            return;
        }
    }
};

你可能感兴趣的:(LeetCode刷题题解记录)