[LeetCode] Combination Sum II

 

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

该题同Combination Sum类似,只不过要求结果数组中不重复

1、先对给定candidates数组排序,这样使找出的每个组合中元素排序一致。便于去重

2、使用std::find()函数对每个新组合判断,将不重复的组合放入结果数组中

3、因为题中要求每个数字只能使用一次,则helper函数中迭代时,idx递增1.

class Solution {
public:
    vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
        vector<vector<int>> res;
        vector<int> tmp;
        sort(candidates.begin(), candidates.end());
        int idx = 0;
        helper(res, tmp, candidates, target, idx);
        return res;
    }
    
    void helper(vector<vector<int>>& res, vector<int>& tmp, vector<int>& candidates, int target, int idx) {
        if (target < 0) {
            return;
        }
        else if (target == 0) {
            if (find(res.begin(), res.end(), tmp) == res.end())
                res.push_back(tmp);
        }
        else {
            for (int i = idx; i < candidates.size(); i++) {
                tmp.push_back(candidates[i]);
                helper(res, tmp, candidates, target - candidates[i], i + 1);
                tmp.pop_back();
            }
        }
    }
};
// 18 ms

 

posted @ 2018-01-25 22:07  immjc  阅读(128)  评论(0编辑  收藏  举报