40. Combination Sum II

2017-10-08  本文已影响0人  Al73r

题目

Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.

Each number in C 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.
For example, given candidate set [10, 1, 2, 7, 6, 1, 5] and target 8,
A solution set is:

[
  [1, 7],
  [1, 2, 5],
  [2, 6],
  [1, 1, 6]
]

分析

这题与第39题的不同点如下

实现

class Solution {
public:
    vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
        vector<vector<int>> ans;
        sort(candidates.begin(), candidates.end());
        ans = solve(candidates, target, 0);
        for(int i=0; i<ans.size(); i++){
            reverse(ans[i].begin(), ans[i].end());
        }
        return ans;
    }
private:
    vector<vector<int>> solve(vector<int>& candidates, int target, int start) {
        vector<vector<int>> ans;
        for(int i=start; i<candidates.size(); i++){
            if(target-candidates[i]<0){
                continue;
            }
            else if(target-candidates[i]==0){
                ans.push_back({candidates[i]});
            }
            else{
                vector<vector<int>> tmp;
                tmp = solve(candidates, target-candidates[i], i+1);
                for(auto v: tmp){
                    v.push_back(candidates[i]);
                    ans.push_back(v);
                }
            }
            while(i+1<candidates.size() && candidates[i]==candidates[i+1])
                i++;
        }
        return ans;
    }
};

思考

这里也删掉了第39题中没用的两行代码。总体来说这道题做得很舒服=_=。

上一篇下一篇

猜你喜欢

热点阅读