【leetcode】Combination Sum II (middle) ☆

时间:2023-02-03 16:38:53

Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums toT.

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]

思路:

把重复的数字看做一个整体,只能出现0-重复次数遍。 这个代码特别慢,不知道为什么 550ms

class Solution {
public:
vector<vector<int> > combinationSum2(vector<int> &num, int target) {
vector<vector<int>> ans;
if(num.empty())
return ans; sort(num.begin(), num.end()); //从小到大排序
recursion(ans, num, , target);
return ans;
} void recursion( vector<vector<int> > &ans, vector<int> candidates, int k, int target)
{
static vector<int> partans; if(target == ) //如果partans中数字的总和已经达到目标, 压入答案
{
ans.push_back(partans);
return;
}
if(k >= candidates.size() || target < )
return; int num = candidates[k];
int copy = ;
while(k < candidates.size() && candidates[k] == num)
{
k++;
copy++;
} recursion(ans, candidates, k, target); //不压入当前数字 for(int i = ; i <= copy; i++)
{
partans.push_back(num); //压入当前数字
recursion(ans, candidates, k , target - i * num); //后面只压入大于当前数字的数,避免重复
} //恢复数据
while(!partans.empty() && partans.back() == num)
{
partans.pop_back();
} }
};

大神的13ms代码,感觉和我的差距不大,为什么速度快这么多。

class Solution {
vector <int> path;
vector < vector <int> > res;
public:
vector<vector<int> > combinationSum2(vector<int> &num, int target) {
sort(num.begin(), num.end());
gen(, target, num);
return res;
}
void gen(int index, int sum, vector <int> &nums) {
if (sum == ) {
res.push_back(path);
return;
} for (int i = index; i < nums.size(); i++) { //只压入序号大于等于i的数字 避免重复
if (sum - nums[i] < ) return;
if (i && nums[i] == nums[i - ] && index < i) continue; //每次递归相同的数字只压入一次
path.push_back(nums[i]); //这里不需要不压入nums[i]的情况,因为循环到后面时自然就是未压入该数的情况了
gen(i + , sum - nums[i], nums);
path.pop_back();
}
}
};