[LeetCode]Combination Sum II

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] 

 

dfs,深搜遍历,set去重,很好理解。

 1 class Solution {
 2 public:
 3     void dfs(vector<int> candidates,int target,int start,vector<int> tmp,set<vector<int>>& result_set)
 4     {
 5         int sum=0;
 6         for(int i=0;i<tmp.size();i++)
 7         {
 8             sum+=tmp[i];
 9         }
10         if(sum==target)
11         {
12             sort(tmp.begin(),tmp.end());
13             result_set.insert(tmp);
14             return;
15         }
16         else if(sum>target)
17         {
18             return;
19         }
20         for(int i=start;i<candidates.size();i++)
21         {
22             tmp.push_back(candidates[i]);
23             dfs(candidates,target,i+1,tmp,result_set);
24             tmp.pop_back();
25         }
26     }
27     vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
28         vector<int> tmp;
29         set<vector<int>> result_set;
30         vector<vector<int>> result;
31         dfs(candidates,target,0,tmp,result_set);
32         set<vector<int>>::iterator it;
33         for(it=result_set.begin();it!=result_set.end();it++)
34         {
35             result.push_back(*it);
36         }
37         return result;
38     }
39 };

 

posted @ 2015-09-17 10:16  Sean_le  阅读(176)  评论(0编辑  收藏  举报