LeetCode 39. Combination Sum
原题链接
简单
作者:
unco
,
2020-08-05 17:29:53
,
所有人可见
,
阅读 382
C++ 代码
class Solution {
public:
vector<vector<int>> res;
vector<int> path;
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
dfs(candidates, target, 0);
return res;
}
void dfs(vector<int>& nums, int target, int cur){
//cur表示当前累加和
if(cur==target){
res.push_back(path); return;
}else if(cur>target){
return;
}else {
for(int i=0; i<nums.size(); i++){
//避免重复,只向后找
if(!path.empty() && nums[i]<path[path.size()-1])
continue;
cur+=nums[i];
path.push_back(nums[i]);
dfs(nums,target,cur);
cur-=nums[i];
path.pop_back();
}
}
}
};