Lintcode153.Combination Sum II

Posted Vincent丶

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Lintcode153.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;
            }
        }
    }
};

 

以上是关于Lintcode153.Combination Sum II的主要内容,如果未能解决你的问题,请参考以下文章

lintcode:单词切分

Lintcode017.Subsets

lintcode入门篇十六

LintCode-不同的子序列

lintcode入门篇五

[LintCode] Palindrome Partitioning II