- 调用size(),比直接用一个int储存然后调用int要慢很多
int n=nums.size();
for (int i=n-2;i>=0;i--)
{
........
}
比
for (int i=nums.size()-2;i>=0;i--)
{
/
}
时间上要短一些
class Solution {
public:
vector<vector<int>> ans;
vector<int> t;
void search(vector<int>& candidates, int begin,int target)
{
int size=candidates.size();
for (int i=begin;i<size;i++)
{
if (candidates[i]<target)
{
t.push_back(candidates[i]);
search(candidates,i,target-candidates[i]);
t.pop_back();
}
else if (candidates[i]==target)
{
t.push_back(candidates[i]);
ans.push_back(t);
t.pop_back();
}
else return;
}
return;
}
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
sort(candidates.begin(), candidates.end());
search(candidates,0,target);
return ans;
}
};
比
class Solution {
public:
void search(vector<vector<int>> &ans,vector<int>& candidates, int begin,int target,vector<int>& temp)
{
vector<int> t;
int size=candidates.size();
for (int i=begin;i<size;i++)
{
if (candidates[i]<target)
{
t=temp;
t.push_back(candidates[i]);
//for (int n:t) cout<<n<<" ";
//cout<<endl;
search(ans,candidates,i,target-candidates[i],t);
}
else if (candidates[i]==target)
{
t=temp;
t.push_back(candidates[i]);
ans.push_back(t);
}
else return;
}
return;
}
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
vector<vector<int>> ans;
vector<int> t;
t.clear();
sort(candidates.begin(), candidates.end());
search(ans,candidates,0,target,t);
return ans;
}
};
耗时更久。应该使用引用引进参数。