leetcode39. 组合总和 medium
题目描述:
给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。
candidates 中的数字可以无限制重复被选取。
说明:
所有数字(包括 target)都是正整数。
解集不能包含重复的组合。
示例 1:
输入: candidates = [2,3,6,7], target = 7,
所求解集为:
[
[7],
[2,2,3]
]
示例 2:
输入: candidates = [2,3,5], target = 8,
所求解集为:
[
[2,2,2,2],
[2,3,3],
[3,5]
]
解题思路:
套路again,回溯法
因为要求解不重复,所以我们规定这次取了下标index的数,下次只能从index及index后面取数,并且我们每次调用新的递归函数时,此时的target要减去当前数组的的数,具体看代码如下:
代码:
class Solution {
public:
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
vector<int> one;
vector<vector<int>> ret;
sort(candidates.begin(), candidates.end()); // 排序 剪枝
dfs(ret, one, candidates, 0, target);
return ret;
}
void dfs(vector<vector<int>> &ret, vector<int> &one, vector<int> &candidates, int start_idx, int target){
if (target == 0){
ret.push_back(one);
return;
}
if (target < 0)
return;
for (int i = start_idx; i<candidates.size() && target >= candidates[i]; i++){
one.push_back(candidates[i]);
dfs(ret, one, candidates, i, target-candidates[i]);
one.pop_back();
}
}
};
class Solution {
public:
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
vector<vector<int>> res;
vector<int> out;
dfs(candidates, target, 0, out, res);
return res;
}
void dfs(vector<int>& candidates, int target, int index, vector<int>& out, vector<vector<int>>& res) {
if (target < 0) return;
if (target == 0) {res.push_back(out); return;}
for (int i = index; i < candidates.size(); ++i) {
out.push_back(candidates[i]);
dfs(candidates, target - candidates[i], i, out, res);
out.pop_back();
}
}
};
//自己写的,稍显啰嗦
class Solution {
public:
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
if(candidates.empty())
return {};
vector<vector<int>> res;
vector<int> out;
dfs(candidates,out,res,0,0,target);
return res;
}
void dfs(vector<int> &candidates,vector<int>& out, vector<vector<int>> &res, int index,int cur,int target){
if(cur==target){
res.push_back(out);
return;
}
for(int i=index;i<candidates.size();++i){
int sum=candidates[i]+cur;
if(sum>target) continue;
else {
out.push_back(candidates[i]);
dfs(candidates,out,res,i,sum,target);
out.pop_back();
}
}
}
};