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

【Lintcode】153.Combination Sum II

时间:2017-05-17 23:41:37      阅读:288      评论:0      收藏:0      [点我收藏+]

标签:strong   pop   ber   code   back   oid   find   ida   bre   

题目:

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.

 Example

Given candidate set [10,1,6,7,2,1,5] and target 8,

A solution set is:

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

题解:

  主要是去重复,多个方法,之前已经介绍过。利用set

Solution 1 ()

class Solution {
public:
    vector<vector<int> > combinationSum2(vector<int> &num, int target) {
        vector<vector<int> > res;
        vector<int> cur;
        sort(num.begin(), num.end());
        dfs(res, cur, num, target, 0);
        
        return res;
    }
    void dfs(vector<vector<int> > &res, vector<int> &cur, vector<int> &num, int target, int pos){
        if (!num.empty() && target == 0) {
            res.push_back(cur);
            return;
        }
        for (int i = pos; i < num.size(); ++i) {
            if(i > pos && num[i] == num[i-1]) {
                continue;
            }
            if (target - num[i] >= 0) {
                cur.push_back(num[i]);
                dfs(res, cur, num, target - num[i], i + 1);
                cur.pop_back();
            } else {
                break;
            }
        }
    }
};

 

【Lintcode】153.Combination Sum II

标签:strong   pop   ber   code   back   oid   find   ida   bre   

原文地址:http://www.cnblogs.com/Atanisi/p/6869805.html

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