首页 > 代码库 > 【Lintcode】153.Combination Sum II

【Lintcode】153.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.

 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