LeetCode 39. 组合总和(C++)
实现:深度优先搜索
class Solution {
public:
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
DFS(0,0,target,candidates.size(),candidates);
return total;
}
private:
vector<vector<int> > total;
vector<int> temp;
void DFS(int index,int sum,int target,int n,vector<int>& candidates){
if(sum==target) {
total.push_back(temp);
return;
}
if(sum > target) return;
for(int i = index;i<candidates.size();i++){
temp.push_back(candidates[i]);
DFS(i,sum+candidates[i],target,n,candidates);
temp.pop_back();
}
}
};