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]
Have you met this question in a real interview?
思路:还是沿着问题1的解题思路,需要额外注意的是重复问题,如:[1,1,1] target=1,得到的结果不能是三个[1],那么如果消除重复呢,最简单的方法就是用set容器
class Solution {
public:
vector<vector<int>> res;
set<vector<int>> result;
void backtrace(vector<int> v,vector<int>&num,int target,int pos,int sum)
{
if(sum==target)
result.insert(v);//res.push_back(v);
else if(sum>target||pos>=num.size())
return ;
else if(sum<target){
for(int i=pos;i<num.size();i++)
{
vector<int> tmp(v);
tmp.push_back(num[i]);
backtrace(tmp,num,target,i+1,sum+num[i]);
}
}
}
vector<vector<int> > combinationSum2(vector<int> &num, int target) {
if(num.size()<1)
return res;
sort(num.begin(),num.end());
vector<int> v;
backtrace(v,num,target,0,0);
res.assign(result.begin(),result.end());
return res;
}
};
Submission Result: Time Limit Exceeded
Last executed input: [6,23,31,29,16,25,14,7,14,17,9,24,24,13,26,14,30,26,24,16,20,8,27,25,16,14,18,12,7,27,16,9,7,13,25,19,33,26,21,5,9,18,16,20,26,7,21,21,21,32,24,28,27,17,18,9,18,23,16,20,15,19,16,9], 24
但是得到TLE,这是怎么回事呢?
分析可能的原因在于backtrace中连续声明并初始化tmp对象,带来了额外的时间开销。
优化该段代码:
class Solution {
public:
vector<vector<int>> res;
set<vector<int>> result;
void backtrace(vector<int> &v,vector<int>&num,int target,int pos,int sum)
{
if(sum==target)
result.insert(v);//res.push_back(v);
else if(sum>target||pos>=num.size())
return ;
else if(sum<target){
for(int i=pos;i<num.size();i++)
{
v.push_back(num[i]);
backtrace(v,num,target,i+1,sum+num[i]);
v.pop_back();
}
}
}
vector<vector<int> > combinationSum2(vector<int> &num, int target) {
if(num.size()<1)
return res;
sort(num.begin(),num.end());
vector<int> v;
backtrace(v,num,target,0,0);
res.assign(result.begin(),result.end());
return res;
}
};
Submission Result: Accepted