示例3
输入: candidates = [2], target = 1
输出: []
示例4
输入: candidates = [1], target = 1
输出: [[1]]
示例5
输入: candidates = [1], target = 2
输出: [[1,1]]
提示
-
1 <= candidates.length <= 30
-
1 <= candidates[i] <= 200
-
candidate 中的每个元素都是独一无二的。
-
1 <= target <= 500
这题就是要在一个无重复元素的数组中找出和为target的所有数的组合,如果我们直接用数组的长度作为递归深度直接套循环,很大程度上会导致超时,所以我们要加上一些剪枝,以及对我们选取数的总和的统计
下面进入代码
首先主函数中初始化ans容器和temp容器,用于存储所有答案和当前递归的合理答案,获取给出数组长度,然后进入dfs函数
class Solution {
public:
int n;
vector<vector> ans;
vector temp;
vector<vector> combinationSum(vector& candidates, int target) {
n = candidates.size();
dfs(candidates, target, 0);
return ans;
}
};
dfs函数中,出口条件为当前temp容器中存储的数的总和等于target
void dfs(vector& candidates, int target, int u) {
if(count(temp) == target) {
ans.push_back(temp);
return;
}
}
然后是遍历整个candidates数组,寻找下一个数,这里要注意遍历起点就是u,也就是递归深度,这是为了防止出现组合重复,这里还有个点要注意就是为了避免一些无用的计算,我们在添加当前数的时候,可以对它进行一个检测,如果加了这个数导致总和大于target,就可以直接跳过这个数,反之不跳过
void dfs(vector& candidates, int target, int u) {
if(count(temp) == target) {
ans.push_back(temp);
return;
}
for(int i = u; i < n; i++) {
if(count(temp) + candidates[i] > target)
continue;
}
}
然后是回溯的写法,这里要注意我们给u传入的值是i,因为元素是可以重复选取的,但是不能是0,如果起点从0开始,就会导致有重复的组合出现
void dfs(vector& candidates, int target, int u) {
if(count(temp) == target) {
ans.push_back(temp);
return;
}
for(int i = u; i < n; i++) {
if(count(temp) + candidates[i] > target)
continue;
temp.push_back(candidates[i]);
dfs(candidates, target, i);
temp.pop_back();
}
}
总结
根据路线图上的重点去进行有针对性的学习,在学习过程中,学会写笔记,做总结。
这里分享一些前端学习笔记:
-
html5 / css3 学习笔记
-
JavaScript 学习笔记
-
Vue 学习笔记