要求:和为target的组合,可以重复用数组中的数
思路:回溯,注意下次找的数大于等于这次的,剪枝在注释部分,时间超过68%,空间85%
class Solution {
public:
vector<vector<int>> v;
vector<int> tmp;
void dfs(vector<int>& candidates,int &target,int sum,int start){
if(sum==target){
v.push_back(tmp);
return;
}
for(int i=start;i<candidates.size();++i){
if(sum+candidates[i]>target)return;//剪枝
tmp.push_back(candidates[i]);
dfs(candidates,target,sum+candidates[i],i);
tmp.pop_back();
}
}
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
sort(candidates.begin(),candidates.end());
dfs(candidates,target,0,0);
return v;
}
};