Skip to content

Latest commit

 

History

History
executable file
·
61 lines (55 loc) · 1.66 KB

0040. Combination Sum II.md

File metadata and controls

executable file
·
61 lines (55 loc) · 1.66 KB

40. Combination Sum II, medium

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

// 12ms, 83%
class Solution {
private:
    vector<vector<int>> cmbSum(vector<int>& candidates, const vector<int>& stage, int start, int target) {
        vector<vector<int>> res;
        for (int i = start; i < candidates.size(); i++) {
            if (i > start && candidates[i] == candidates[i-1])
                continue; 
            auto val = candidates[i];
            if (val > target) break;
            if (val == target) {
                res.push_back(stage);
                res.back().push_back(val);
                break;
            }
            
            auto stage2(stage);
            stage2.push_back(val);
            auto r = cmbSum(candidates, stage2, i+1, target - val);
            if (!r.empty()) {
                res.insert(res.end(), r.begin(), r.end());
            }
        }
        return res;
    }
public:
    vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
        sort(candidates.begin(), candidates.end());
        vector<int> stage;
        return cmbSum(candidates, stage, 0, target);
    }
};