[LeetCode] 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 (a1a2, … , 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] 

类似与之前的Combination Sum的DFS,有一点需要注意,如何避免重复。如果两个数相同,我们先用前一个数,只有当前一个数用了,这个数才能使用。

例如:1 1。

当我们要使用第二个1时,我们要检查他的前面一个1是否使用了,当未被使用时第二个1就不能使用。

 1 class Solution {
 2 private:
 3     vector<vector<int> > ret;
 4     vector<int> a;
 5 public:
 6     void solve(int dep, int maxDep, vector<int> &num, int target)
 7     {
 8         if (target < 0)
 9             return;
10             
11         if (dep == maxDep)
12         {
13             if (target == 0)
14             {
15                 vector<int> res;
16                 for(int i = 0; i < maxDep; i++)
17                     for(int j = 0; j < a[i]; j++)
18                         res.push_back(num[i]);
19                 ret.push_back(res);
20             }
21             
22             return;
23         }
24         
25         for(int i = 0; i <= min(target / num[dep], 1); i++)
26         {
27             a[dep] = i;
28             
29             if (i == 1 && dep > 0 && num[dep-1] == num[dep] && a[dep-1] == 0)
30                 continue;
31                 
32             solve(dep + 1, maxDep, num, target - i * num[dep]);
33         }
34     }
35     
36     vector<vector<int> > combinationSum2(vector<int> &num, int target) {
37         // Start typing your C/C++ solution below
38         // DO NOT write int main() function
39         sort(num.begin(), num.end());
40         a.resize(num.size());
41         ret.clear();
42         if (num.size() == 0)
43             return ret;
44             
45         solve(0, num.size(), num, target);
46         
47         return ret;
48     }
49 };
原文地址:https://www.cnblogs.com/chkkch/p/2745125.html