39. 组合总和
?做题思路or感想
这里依旧是找组合,故依旧是用回溯法
而因为这里的元素是可以重复选取的,所以这里的startIndex在递归时不需要+1,或者直接干脆不用startIndex就可以了
但是为了防止[2,2,3],[2,3,2]这种重复,所以需要安排一下子集都是要递增的就好了
class Solution {
public:
vectortemp;
vector>result;
//这里直接取消了startIndex,不需要再强制性的缩小取值范围了,因为单个值可以无限的取
void dfs(vector& candidates, int target) {
if (target < 0)return; //容易想到且有效的剪枝
if (target == 0) { //递归中止条件
result.push_back(temp);
return;
}
//处理数据
for (int i = 0; i < candidates.size(); i++) {
//这里if是维持子集是单调递增的!
if (temp.size() != 0 && temp.back() <= candidates[i] || temp.size() == 0) {
temp.push_back(candidates[i]);
dfs(candidates, target - candidates[i]);
temp.pop_back();//回溯
}
}
}
vector> combinationSum(vector& candidates, int target) {
dfs(candidates, target);
return result;
}
};