[Leetcode] combination sum ii 组合之和

时间:2024-01-04 21:31:20

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的解要跳过。这时也不过跳过由重复数字组成的解,因为,首次出现重复的数字时,已经给出了由重复数字组合等于给定值的情况。

代码如下:

 class Solution {
public:
vector<vector<int> > combinationSum2(vector<int> &num, int target)
{
vector<vector<int>> res;
vector<int> midVal;
sort(num.begin(),num.end());
DFS(res,midVal,num,target,);
return res;
} void DFS(vector<vector<int>> &res,vector<int> &midVal,vector<int> &num,int target,int start)
{
if(target<)
return;
else if(target==)
res.push_back(midVal);
else
{
for(int i=start;i<num.size();i++)
{
if(i>start&&num[i]==num[i-]) //
continue;
midVal.push_back(num[i]);
DFS(res,midVal,num,target-num[i],i+);
midVal.pop_back();
}
}
}
};