leetcode第39题--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.
  • Elements in a combination (a1, a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
  • 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]

国家德比毕。记录此题。

和上题的意思差不多,不同在于candidates的每个数在一个组合中只能用一次。

一开始以为很简单,只要把上一题的back函数传入的下标加1就可以了。这还不够,还要避免一些重复的case。例如[1,1]的时候,目标是1的时候,如何只输出一个答案。所以我们应该注意到,在每一层中,如果之前一个数和当前的数相同,并且之前那个数是已经进入tmp尝试过的,那么当前的就应该跳过,因为这个情况之前已经判断过了,再判断就是重复了。一开始我用candidates[i-1]和candidates[i]相比是否相同,发现还是不行。因为candidades[i-1]不一定在之前考虑过。很简单,就是在[1,1]的case中目标是2的话,如果用candidates的i-1和i的相比的话就会出现错误,因为在写成树结构的时候,第二层中的第一个1是没有考虑的,所以第二个1不会重复(简单画一个二叉树就知道了)。

class Solution {
public:
void back39(vector<vector<int> > &ans, vector<int> &candidates, vector<int> &tmp, int target, int cur)
{
    if (0 == target)
    {
        ans.push_back(tmp); 
        return;
    }
    int rp = -1;
    for (int i = cur; i < candidates.size(); ++i)
    {
        //需要判断当前的candidate是不是和上一次加进去并且删除了的一样,如果一样的话因为是同一层所以跳过
        //本来想用candidates[i-1]和candidates[i]比较,但并不是所有的前一个都被列入到tmp中,只有列入到tmp中的才算重复
        //例如当输入为[1,1] 目标为2的时候用candidates[i-1]和candidates[i]就不行
        if (rp == candidates[i]) 
            continue;
        if (candidates[i] <= target) 
        {
            rp = candidates[i]; // 记录,为了和下次进行比较,如果一样则continue
            tmp.push_back(candidates[i]);
            back39(ans, candidates, tmp, target - candidates[i], i + 1);       
            tmp.pop_back();
        }
        if (candidates[i] > target)
        {
            return;
        }
    }
}
    vector<vector<int> > combinationSum2(vector<int> &num, int target) 
    {
        std::sort(num.begin(), num.end());
        vector<vector<int> > ans;
        vector<int> tmp;
        back38(ans, num, tmp, target, 0);
        return ans;
    }
};

 

posted on 2014-10-26 01:56  higerzhang  阅读(438)  评论(0编辑  收藏  举报