- 组合总和
给定一个无重复元素的正整数数组 candidates 和一个正整数 target ,找出 candidates 中所有可以使数字和为目标数 target 的唯一组合。
candidates 中的数字可以无限制重复被选取。如果至少一个所选数字数量不同,则两种组合是唯一的。
对于给定的输入,保证和为 target 的唯一组合数少于 150 个。
示例 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]]
示例 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
第一次忽略了要保证每个满足条件的组合中的数字出现次数不同。
其运行结果是这样子的
这是代码
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> ans = new ArrayList<>();
int n =candidates.length;
Deque<Integer> num_stack = new ArrayDeque<>();//用来存储已经选择的数字
dfs(n,0,candidates,target,num_stack,ans);
return ans;
}
public static void dfs (int n, int total, int[] candidates,int target,Deque<Integer> num_stack,List<List<Integer>> ans) {
//结束条件,等于target则加入到ans,如果大于的话就不满足,直接return
if(total == target){
ans.add(new ArrayList<>(num_stack));
return;
}else if(total > target){
return;
}
for(int i = 0;i<n;i++){
num_stack.push(candidates[i]);//选择数字加入栈
//进入下一个数字的dfs
dfs(n,total+candidates[i],candidates,target,num_stack,ans);
num_stack.pop();//用完就出栈
}
}
这里是自己构造的树错了,自己构造的是这样子的模式。
但是这样子就会将[2,2,3]选择了,但是对于[2,3,2],[3,2,2]这种也会被选择,没有起到筛选的左右。
正确的树应该是像题解的这种:
每一层表示对当前的数是否选择。
代码如下:
class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> ans = new ArrayList<>();
int n =candidates.length;
Deque<Integer> num_stack = new ArrayDeque<>();//用来存储已经选择的数字
dfs(n,0,candidates,target,num_stack,ans);
return ans;
}
public static void dfs (int n, int index , int[] candidates,int target,Deque<Integer> num_stack,List<List<Integer>> ans) {
//结束条件,等于target则加入到ans,如果大于的话就不满足,直接return
if(index == n ){
return;
}
if(target ==0){
ans.add(new ArrayList<>(num_stack));
return;
}
//跳过
dfs(n,index+1,candidates,target,num_stack,ans);
if(target - candidates[index] >=0){
num_stack.push(candidates[index]);//选择数字加入栈
//进入下一个数字的dfs
dfs(n,index,candidates,target-candidates[index],num_stack,ans);
num_stack.pop();//用完就出栈
}
}
}
`dfs(n,index+1,candidates,target,num_stack,ans);
上面这句代码是模拟树的操作,开始都不进行选择,都跳过。
下面这个代码 是模拟选择数字的操作。
if(target - candidates[index] >=0){
num_stack.push(candidates[index]);//选择数字加入栈
//进入下一个数字的dfs
dfs(n,index,candidates,target-candidates[index],num_stack,ans);
num_stack.pop();//用完就出栈
}