题意
给定一个不重复的序列和一个 target ,序列中的每个数可以取多次,求取出数的和为 target 的方案
思路
直接DFS求出每个数要取几个即可
代码
class Solution {
public:
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
sort(candidates.begin(), candidates.end());
vector<int>now;
vector<vector<int> >ans;
findAns(candidates, ans, now, 0, target);
return ans;
}
private:
void findAns(vector<int>& candidates, vector<vector<int> >& ans, vector<int>& now, int id, int target){
if(target == 0){
ans.push_back(now);
return ;
}
if(id >= candidates.size()) return ;
for(int i = 0; i * candidates[id] <= target; i++){
for(int j = 0; j < i; j++){
now.push_back(candidates[id]);
}
findAns(candidates, ans, now, id + 1, target - i * candidates[id]);
for(int j = 0; j < i; j++){
now.pop_back();
}
}
}
};