[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 (a 1, a 2, … , a k) must be in non-descending order. (ie, a 1 ≤ a 2 ≤ … ≤ a k).
  • The solution set must not contain duplicate combinations.

For example, given candidate set10,1,2,7,6,1,5and target8, 
A solution set is: 
[1, 7]
[1, 2, 5]
[2, 6]
[1, 1, 6]

 题意:给定值T,在C中找到和为T的组合,要求:C中的每个元素只能出现一次,不能用有重复组合。

思路:正确理解,C中的每个元素只能出现一次!如例子中的[1,1,6],只是数组中的每个元素只能出现一次,不是说,元素值相等的只能出现一次。要给出所以满足条件的解,这题是典型的深搜。在深搜之前要注意到题中要求,每个组合中元素的值要是非降序的,所以,要先对数组进行排序。因为数组中元素的值有重复的情况,所以在写DFS函数时,要跳过重复的元素。参考了Grandyang的写法。比如排序以后,题中例子变为[1,1,2,5,6,7,10],解中给出以第一个元素1和7组合的解了,以第二元素1和7的解要跳过。这时也不过跳过由重复数字组成的解,因为,首次出现重复的数字时,已经给出了由重复数字组合等于给定值的情况。

代码如下:

 1 class Solution {
 2 public:
 3     vector<vector<int> > combinationSum2(vector<int> &num, int target) 
 4     {
 5         vector<vector<int>> res;
 6         vector<int> midVal;
 7         sort(num.begin(),num.end());
 8         DFS(res,midVal,num,target,0);
 9         return res;    
10     }
11 
12     void DFS(vector<vector<int>> &res,vector<int> &midVal,vector<int> &num,int target,int start)
13     {
14         if(target<0)
15             return;
16         else if(target==0)
17             res.push_back(midVal);
18         else
19         {
20             for(int i=start;i<num.size();i++)
21             {
22                 if(i>start&&num[i]==num[i-1])    //
23                     continue;
24                 midVal.push_back(num[i]);
25                 DFS(res,midVal,num,target-num[i],i+1);
26                 midVal.pop_back();
27             }
28         }
29     }
30 };
原文地址:https://www.cnblogs.com/love-yh/p/7150912.html