[Leetcode 99] 40 Combination Sum II

Problem:

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] 

 

Analysis:

This is a dfs problem. First sort the given array to keep the element ordered. Then use dfs to search for candidate solutions. 

After get a solution that sum is equal to taget. Before push it into the result vector. first need to check whether there is already a duplicated solution in the result vector. If not, then we are safe to add it into the result vector.

 

Code:

 1 class Solution {
 2 public:
 3 vector<vector<int> > res;
 4 vector<int> t_res;
 5 int t;
 6 
 7 vector<vector<int> > combinationSum2(vector<int> &num, int target) {
 8     // Start typing your C/C++ solution below
 9     // DO NOT write int main() function
10     res.clear();
11     t_res.clear();
12     t = target;
13 
14     if (num.size() == 0) return res;
15 
16     sort(num.begin(), num.end());
17 
18     dfs(0, 0, num);
19 
20     return res;
21 }
22     
23 private:
24     bool dup() {
25 
26     for (int i=0; i<res.size(); i++) {
27         if(res[i].size() == t_res.size()) {
28             int j;
29             for (j=0; j<res[i].size(); j++) {
30                 if (res[i][j] != t_res[j])
31                     break;
32             }
33 
34             if (j == res[i].size())
35                 return true;
36         }
37     }
38 
39     return false;
40 }
41 
42 void dfs(int idx, int sum, vector<int> &num) {
43     if (sum == t && !dup()) {
44         res.push_back(t_res);
45         return ;
46     } else if (sum > t)
47         return ;
48 
49     for (int i=idx; i<num.size(); i++) {
50         t_res.push_back(num[i]);
51         dfs(i+1, sum+num[i], num);
52         t_res.pop_back();
53     }
54 }
55 };
View Code

 

 

posted on 2013-08-07 05:06  freeneng  阅读(161)  评论(0编辑  收藏  举报

导航