组合问题:N个数里面按一定规则找出k个数的集合,下面是常见的回溯算法题目解决组合问题。
leedcode77. 组合
给定两个整数 n 和 k,返回范围 [1, n] 中所有可能的 k 个数的组合。
你可以按 任何顺序 返回答案。
回溯法抽象为树形结构后,其遍历过程就是:for循环横向遍历,递归纵向遍历,回溯不断调整结果集。
class Solution {
//回溯算法
public List<List<Integer>> combine(int n, int k) {
//List<Integer> path=new ArrayList<>();
Deque<Integer> path=new LinkedList<>();
List<List<Integer>> res=new ArrayList<>();
dfs(n,k,1,path,res);
return res;
}
public void dfs(int n,int k,int startIndex, Deque<Integer> path,List<List<Integer>> res){
if(path.size()==k){
//终止条件
res.add(new ArrayList<>(path));
return;
}
//控制树的横向遍历
for(int i=startIndex;i<=n-(k-path.size())+1;i++){
//剪枝处理
path.add(i);
dfs(n,k,i+1,path,res);
path.removeLast();//回溯,弹出处理的节点
}
}
}
leedcode216. 组合总和 III
找出所有相加之和为 n 的 k 个数的组合,且满足下列条件:
只使用数字1到9
每个数字 最多使用一次
返回 所有可能的有效组合的列表 。该列表不能包含相同的组合两次,组合可以以任何顺序返回。
示例 1:
输入: k = 3, n = 7 输出: [[1,2,4]] 解释: 1 + 2 + 4 = 7 没有其他符合的组合了。
示例 2:
输入: k = 3, n = 9 输出: [[1,2,6], [1,3,5], [2,3,4]] 解释: 1 + 2 + 6 = 9 1 +
3 + 5 = 9 2 + 3 + 4 = 9 没有其他符合的组合了。
示例 3:
输入: k = 4, n = 1 输出: [] 解释: 不存在有效的组合。
在[1,9]范围内使用4个不同的数字,我们可以得到的最小和是1+2+3+4 = 10,因为10 > 1,没有有效的组合。
class Solution {
List<List<Integer>> result=new ArrayList<>();
Deque<Integer> path=new LinkedList<>();
public List<List<Integer>> combinationSum3(int k, int n) {
dfs(k,n,1,0);
return result;
}
public void dfs(int k,int n,int startIndex,int sum){
//剪枝
if(sum>n){
return;
}
if(k==path.size()){
if(sum==n){
result.add(new ArrayList<>(path));
return;
}
}
for(int i=startIndex;i<=9-(k-path.size())+1;i++){
path.add(i);
sum=sum+i;
dfs(k,n,i+1,sum);
path.removeLast();
sum=sum-i;
}
}
}
leedcode46. 全排列
给定一个不含重复数字的数组 nums ,返回其 所有可能的全排列 。你可以 按任意顺序 返回答案。
示例 1:
输入:nums = [1,2,3] 输出:[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
示例 2:
输入:nums = [0,1] 输出:[[0,1],[1,0]]
示例 3:
输入:nums = [1] 输出:[[1]]
leedcode17. 电话号码的字母组合
给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。答案可以按 任意顺序 返回。
给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。
示例 1:
输入:digits = “23”
输出:[“ad”,“ae”,“af”,“bd”,“be”,“bf”,“cd”,“ce”,“cf”]
示例 2:
输入:digits = “”
输出:[]
示例 3:
输入:digits = “2”
输出:[“a”,“b”,“c”]
如果是一个集合来求组合的话,就需要startIndex。
如果是多个集合取组合,各个集合之间相互不影响,那么就不用startIndex。
本题多个集合取组合因此不用startIndex,每次都从i=0开始。
class Solution {
private List<String> res= new ArrayList<>();
public List<String> letterCombinations(String digits) {
if(digits.length()==0||digits==null){
return res;
}
//0和1无效,2到9有效
String[] s={
"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
//res = new ArrayList<>();
isBackTest(s,digits,0);
return res;
}
//涉及字符串拼接可以使用StringBuilder
StringBuilder temp=new StringBuilder();
//三个参数分别是字符串s,要组合的字符digits,和组合的个数num
private void isBackTest(String[] s, String digits, int num) {
if(num==digits.length()){
//如果要组合的字符长度等于组合个数直接添加并返回
// System.out.println("进来");
res.add(temp.toString());
return;
}
//System.out.println("再进来");
String str=s[digits.charAt(num)-'0'];//比如digits="23",我们可以获取'2'-'0'=2,'3'-'0'=3
for(int i=0;i<str.length();i++){
temp.append(str.charAt(i));//添加字符串中的字符
isBackTest(s,digits,num+1);//递归
temp.deleteCharAt(temp.length()-1);//回溯,减去末尾的元素,此时的num是当前方法的num
}
}
}
leedcode39. 组合总和
给你一个 无重复元素 的整数数组 candidates 和一个目标整数 target ,找出 candidates 中可以使数字和为目标数 target 的 所有 不同组合 ,并以列表形式返回。你可以按 任意顺序 返回这些组合。
candidates 中的 同一个 数字可以 无限制重复被选取 。如果至少一个数字的被选数量不同,则两种组合是不同的。
对于给定的输入,保证和为 target 的不同组合数少于 150 个。
示例 1:
输入:candidates = [2,3,6,7], target = 7 输出:[[2,2,3],[7]]
解释: 2 和 3可以形成一组候选,2 + 2 + 3 = 7 。注意 2 可以使用多次。 7 也是一个候选, 7 = 7 。 仅有这两种组合。
示例 2:
输入: candidates = [2,3,5], target = 8
输出: [[2,2,2,2],[2,3,3],[3,5]]
示例 3:
输入: candidates = [2], target = 1
输出: []
本题和我们之前讲过的77.组合 216.组合总和III 有两点不同:
- 组合没有数量要求
- 元素可无限重复选取
class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
//先排好序后面如果有大于target可以直接返回
Arrays.sort(candidates);
//相比与组合III,这道题增加了同一个元素可以被无限重复选取,还有就是递归结束条件不是第几层而是大于等于target
isBackTest(candidates,target,0,0);
return res;
}
List<List<Integer>> res=new ArrayList<>();
List<Integer> path=new ArrayList<>();
private void isBackTest(int[] candidates, int target, int startIndex,int sum) {
if(sum>target){
return;
}
if(sum==target){
res.add(new ArrayList<>(path));
return;
}
//剪枝条件不符合sum+candidates[i]<=target,连递归都不需要调
for(int i=startIndex;i<candidates.length&&sum+candidates[i]<=target;i++){
sum=sum+candidates[i];
path.add(candidates[i]);
isBackTest(candidates,target,i,sum);//这里不用i+1,表示可以重复读取当前的数
path.remove(path.size()-1);//回溯
sum=sum-candidates[i];
}
}
}
leedcode40. 组合总和 II
给定一个候选人编号的集合 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。
candidates 中的每个数字在每个组合中只能使用 一次 。
注意:解集不能包含重复的组合。
示例 1:
输入: candidates = [10,1,2,7,6,1,5], target = 8,
输出: [ [1,1,6], [1,2,5],[1,7], [2,6] ]
示例 2:
输入: candidates = [2,5,2,1,2], target = 5,
输出: [ [1,2,2], [5] ]
这道题目和39.组合总和如下区别:
本题candidates 中的每个数字在每个组合中只能使用一次。
本题数组candidates的元素是有重复的,而39.组合总和 是无重复元素的数组candidates
最后本题和39.组合总和 要求一样,解集不能包含重复的组合。
本题的难点在于:集合(数组candidates)有重复元素,但还不能有重复的组合。
class Solution {
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
//先进行排序
Arrays.sort(candidates);
//新建一个used数组,用来进行标记和去重
boolean[] used = new boolean[candidates.length];
isBackTest(candidates, target, 0, 0, used);
return result;
}
List<List<Integer>> result=new ArrayList<>();
List<Integer> path=new ArrayList<>();
private void isBackTest(int[] candidates, int target, int sum, int statIndex, boolean[] used) {
// if(sum>target){//已经在for循环的之后进行剪枝了,不会进入递归也不用写这条语句
// return;
// }
if(sum==target){
result.add(new ArrayList<>(path));
return;
}
for(int i=statIndex;i<candidates.length&&candidates[i]+sum<=target;i++){
if(i>0&&candidates[i]==candidates[i-1]&&used[i-1]==false){
//去重
//递归回溯过程可以看成树结构
//used[i - 1] == true,说明同一树枝candidates[i - 1]使用过
//used[i - 1] == false,说明同一树层candidates[i - 1]使用过
//如果当前一个元素和上一个元素(相邻)相同,并且上一个元素的used[i]为false,
//直接continue进行下次循环
continue;
}
path.add(candidates[i]);
sum=sum+candidates[i];
used[i]=true;//代表已经标记为true
isBackTest(candidates,target,sum,i+1,used);
//回溯
path.remove(path.size()-1);
sum=sum-candidates[i];
used[i]=false;//更新标记为false
}
}
}