码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] Combination Sum II

时间:2018-01-25 23:09:56      阅读:175      评论:0      收藏:0      [点我收藏+]

标签:body   block   contain   vector   including   each   positive   bsp   rip   

 

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

 

[LeetCode] Combination Sum II

标签:body   block   contain   vector   including   each   positive   bsp   rip   

原文地址:https://www.cnblogs.com/immjc/p/8353443.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!