题目:
解答:
思路是递归求解,首先序列排序,然后依次对第一个数 a 0 a_0 a0 取 0 → ⌊ t a r g e t a 0 ⌋ 0\to\left\lfloor\dfrac{target}{a_0}\right\rfloor 0→⌊a0target⌋ ,递归处理1-len的序列,这样递归处理
对第i个数,取 0 → ⌊ t a r g e t − s u m p r e a i ⌋ 0\to\left\lfloor\dfrac{target-sum_{pre}}{a_i}\right\rfloor 0→⌊aitarget−sumpre⌋ ,其中 S u m p r e Sum_{pre} Sumpre 是之前已有选取序列之和。
如此处理,将最终符合条件 t a r g e t = = S u m p r e target == Sum_{pre} target==Sumpre 的选取序列保存,即可。
代码:
// 方法一,使用拷贝方式递归处理
class Solution {
public:
void findCompare(vector<int>& candidates,
vector<vector<int>>& result,
vector<int> tmp, //这个需要扩展下去,递归会使用新的vector,防止干扰
int sum,
int index,
int len,
int target){
int num = candidates[index];
if(index == len || num > target - sum) return;
findCompare(candidates, result, tmp, sum, index + 1, len, target);
while(num <= target - sum){
tmp.push_back(num);
sum += num;
if(sum == target)
result.push_back(tmp);
findCompare(candidates, result, tmp, sum, index + 1, len, target);
}
}
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
int len = candidates.size();
sort(candidates.begin(), candidates.end());
vector<vector<int>> result;
vector<int> tmp;
findCompare(candidates, result, tmp, 0, 0, len, target);
return result;
}
};
// 方案二,使用一个数组引用递归处理,更节省空间和省去拷贝时间
class Solution {
public:
void findCompare(vector<int>& candidates,
vector<vector<int>>& result,
vector<int>& tmp,
int sum,
int index,
int index2,
int len,
int target){
int num = candidates[index];
if(index == len || num > target - sum) return;
findCompare(candidates, result, tmp, sum, index + 1, index2, len, target);
while(num <= target - sum){
tmp[index2++] = num;
sum += num;
if(sum == target){
vector<int> vec(tmp.begin(), tmp.begin() + index2);
result.push_back(vec);
}
findCompare(candidates, result, tmp, sum, index + 1, index2, len, target);
}
}
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
int len = candidates.size();
sort(candidates.begin(), candidates.end());
vector<vector<int>> result;
vector<int> tmp(1000, 0);
findCompare(candidates, result, tmp, 0, 0, 0, len, target);
return result;
}
};
更新会同步在我的网站更新(https://zergzerg.cn/notes/webnotes/leetcode/index.html)