问题描述:
方法一:回溯法:(不含剪枝)
对于这类寻找所有可行解的题,我们都可以尝试用「搜索回溯」的方法来解决。
回到本题,我们定义递归函数 dfs(target, combine, idx) 表示当前在 candidates 数组的第 idx 位,还剩 target 要组合,已经组合的列表为 combine。递归的终止条件为 target <= 0 或者 candidates 数组被全部用完。那么在当前的函数中,每次我们可以选择跳过不用第 idx 个数,即执行 dfs(target, combine, idx + 1)。也可以选择使用第 idx 个数,即执行 dfs(target - candidates[idx], combine, idx),注意到每个数字可以被无限制重复选取,因此搜索的下标仍为 idx。
更形象化地说,如果我们将整个搜索过程用一个树来表达,即如下图呈现,每次的搜索都会延伸出两个分叉,直到递归的终止条件,这样我们就能不重复且不遗漏地找到所有可行解:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class combinationSum {
public static List<List<Integer>> combinationSum(int[] condidates,int target){
List<List<Integer>> ans =new ArrayList<List<Integer>>();//新建一个列表用于记录答案
List<Integer> combine =new ArrayList<Integer>();//符合答案的组合
dfs(condidates,target,ans,combine,0);
//定义递归函数 dfs(target, combine, index) 表示当前在 candidates 数组的第 index 位,
// 还剩 target 要组合,已经组合的列表为 combine.
return ans;
}
private static void dfs(int[] condidates, int target, List<List<Integer>> ans, List<Integer> combine, int index) {
if(index==condidates.length){//循环终止条件
return;
}
if(target==0){//符合条件
ans.add(new ArrayList<Integer>(combine));
return;
}
//直接跳过这个数,不选择这个数:第一种情况
dfs(condidates,target,ans,combine,index+1);
//选择这个数:第二种情况
if(target-condidates[index]>=0){
combine.add(condidates[index]);
dfs(condidates,target-condidates[index],ans,combine,index);
combine.remove(combine.size()-1);//????????什么意思呢?状态重置!
}
}
public static void main(String[] args) {
int[] condidates={2,3,6,7};
int target = 7;
List<List<Integer>> ans= combinationSum(condidates,target);
System.out.println(ans.toString());
}
}
方法二:
涉及到了Deque知识点:https://cartoonyu.github.io/cartoon-blog/post/java/queue%E4%B8%8Edeque%E7%9A%84%E5%8C%BA%E5%88%AB/
有空把站和队列补一补:https://blog.youkuaiyun.com/qq_40301026/article/details/98037402
栈:先进后出,队列:先进先出
思路分析:根据示例 1:输入: candidates = [2, 3, 6, 7],target = 7。
候选数组里有 2,如果找到了组合总和为 7 - 2 = 5 的所有组合,再在之前加上 2 ,就是 7 的所有组合;
同理考虑 3,如果找到了组合总和为 7 - 3 = 4 的所有组合,再在之前加上 3 ,就是 7 的所有组合,依次这样找下去。
基于以上的想法,可以画出如下的树形图。建议大家自己在纸上画出这棵树,这一类问题都需要先画出树形图,然后编码实现。
编码通过 深度优先遍历 实现,使用一个列表,在 深度优先遍历 变化的过程中,遍历所有可能的列表并判断当前列表是否符合题目的要求,成为「回溯算法」(个人理解,非形式化定义)。
画出树形图
以输入:candidates = [2, 3, 6, 7], target = 7 为例:
说明:
以 target = 7 为 根结点 ,创建一个分支的时 做减法 ;
每一个箭头表示:从父亲结点的数值减去边上的数值,得到孩子结点的数值。边的值就是题目中给出的 candidate 数组的每个元素的值;
减到 00 或者负数的时候停止,即:结点 00 和负数结点成为叶子结点;
所有从根结点到结点 00 的路径(只能从上往下,没有回路)就是题目要找的一个结果。
这棵树有 44 个叶子结点的值 00,对应的路径列表是 [[2, 2, 3], [2, 3, 2], [3, 2, 2], [7]],而示例中给出的输出只有 [[7], [2, 2, 3]]。即:题目中要求每一个符合要求的解是 不计算顺序 的。下面我们分析为什么会产生重复。
针对具体例子分析重复路径产生的原因(难点)
产生重复的原因是:在每一个结点,做减法,展开分支的时候,由于题目中说 每一个元素可以重复使用,我们考虑了 所有的 候选数,因此出现了重复的列表。
一种简单的去重方案是借助哈希表的天然去重的功能,但实际操作一下,就会发现并没有那么容易。
可不可以在搜索的时候就去重呢?答案是可以的。遇到这一类相同元素不计算顺序的问题,我们在搜索的时候就需要 按某种顺序搜索。具体的做法是:每一次搜索的时候设置 下一轮搜索的起点 begin,请看下图。
即:从每一层的第 22 个结点开始,都不能再搜索产生同一层结点已经使用过的 candidate 里的元素。
友情提示:如果题目要求,结果集不计算顺序,此时需要按顺序搜索,才能做到不重不漏。「力扣」第 47 题( 全排列 II https://leetcode-cn.com/problems/permutations-ii/)、「力扣」第 15 题( 三数之和https://leetcode-cn.com/problems/3sum/ )也使用了类似的思想,使得结果集没有重复。
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;
public class combinationSum1 {
public static List<List<Integer>> combinationSum1(int[] candidates,int target){
List<List<Integer>> res=new ArrayList<>();
int len=candidates.length;
if(len==0){
return res;
}
Deque<Integer> path=new ArrayDeque<>();
dfs(candidates,0,len,target,path,res);
return res;
}
/**
* @param candidates 候选数组
* @param begin 搜索起点
* @param len 冗余变量,是 candidates 里的属性,可以不传
* @param target 每减去一个元素,目标值变小
* @param path 从根结点到叶子结点的路径,是一个栈
* @param res 结果集列表
*/
private static void dfs(int[] candidates, int begin, int len, int target, Deque<Integer> path, List<List<Integer>> res) {
if(target<0){//若目标值小于0,结束
return;
}
if(target==0){//若目标值等于0,加入到结果集种
res.add(new ArrayList<>(path));
}
for(int i=begin;i<len;i++){//重点是这里从begin开始搜索,每一次搜索的时候设置 下一轮搜索的起点 begin
path.addLast(candidates[i]);//*************
注意:由于每一个元素可以重复使用,下一轮搜索的起点依然是 i,这里非常容易弄错
dfs(candidates,i,len,target-candidates[i],path,res);//i!!!
//状态重置************8
path.removeLast();
}
}
public static void main(String[] args) {
int[] candidates={2,3,6,7};
int target=7;
List<List<Integer>> res=combinationSum1(candidates,target);
System.out.println(res.toString());
}
}
剪枝提速:
如果 target 减去一个数得到负数,那么减去一个更大的数依然是负数,同样搜索不到结果。基于这个想法,我们可以对输入数组进行排序,添加相关逻辑达到进一步剪枝的目的;
import java.util.*;
public class combinationSum2 {
public static List<List<Integer>>combinationSum2(int[] candidates,int target){
int len =candidates.length;
List<List<Integer>>res=new ArrayList<>();
if(len==0){
return res;
}
Arrays.sort(candidates);
Deque<Integer>path=new ArrayDeque<>();
dfs(candidates,0,len,target,path,res);
return res;
}
private static void dfs(int[] candidates, int begin, int len, int target, Deque<Integer> path, List<List<Integer>> res) {
if(target==0){//由于进入更深层的时候,小于 0 的部分被剪枝,因此递归终止条件值只判断等于 0 的情况
res.add(new ArrayList<>(path));
return;
}
for (int i = begin; i < len; i++) {
if(target-candidates[i]<0){ // 重点理解这里剪枝,前提是候选数组已经有序,
break;
}
path.addLast(candidates[i]);//**************
dfs(candidates,i,len,target-candidates[i],path,res);
path.removeLast();
}
}
public static void main(String[] args) {
int[] candidates={2,3,6,7};
int target=7;
List<List<Integer>> res=combinationSum2(candidates,target);
System.out.println(res.toString());
}
}
总结:
什么时候使用 used 数组,什么时候使用 begin 变量
有些朋友可能会疑惑什么时候使用 used 数组,什么时候使用 begin 变量。这里为大家简单总结一下:
排列问题,讲究顺序(即 [2, 2, 3] 与 [2, 3, 2] 视为不同列表时),需要记录哪些数字已经使用过,此时用 used 数组;
组合问题,不讲究顺序(即 [2, 2, 3] 与 [2, 3, 2] 视为相同列表时),需要按照某种顺序搜索,此时使用 begin 变量。
注意:具体问题应该具体分析, 理解算法的设计思想 是至关重要的,请不要死记硬背。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/combination-sum
链接:https://leetcode-cn.com/problems/combination-sum/solution/hui-su-suan-fa-jian-zhi-python-dai-ma-java-dai-m-2/