1.组合问题
组合类问题相当于求满足要求的集合,回溯时需要index,每次从index开始
1.leetcode77 组合
给定两个整数 n
和 k
,返回范围 [1, n]
中所有可能的 k
个数的组合。你可以按 任何顺序 返回答案。(相当于最基础的回溯)
示例 1:
输入:n = 4, k = 2
输出:
[[2,4],[3,4],[2,3],[1,2],[1,3],[1,4],]
示例 2:
输入:n = 1, k = 1
输出:[[1]]
class Solution {
public void recursion(List<List<Integer>> res, List<Integer> tmp, int n, int k, int index){
if(tmp.size()==k){
res.add(new ArrayList<>(tmp));
return;
}
for(int i=index;i<=n;i++){
tmp.add(i);
recursion(res,tmp,n,k,i+1);
tmp.remove(tmp.size()-1);
}
}
public List<List<Integer>> combine(int n, int k) {
List<List<Integer>> res = new ArrayList<>();
List<Integer> tmp = new ArrayList<>();
recursion(res, tmp, n, k, 1);
return res;
}
}
2. leetcode216 组合总和lll
找出所有相加之和为 n 的 k 个数的组合,且满足下列条件:
只使用数字1到9
每个数字 最多使用一次
返回 所有可能的有效组合的列表 。该列表不能包含相同的组合两次,组合可以以任何顺序返回。
示例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
没有其他符合的组合了。
class Solution {
public void recursion(List<List<Integer>> res, List<Integer> tmp, int k, int n, int sum, int index){
if(tmp.size()==k && sum==n){
res.add(new ArrayList<>(tmp));
return;
}
for(int i=index;i<=9;i++){
if(sum+i>n)
break;
tmp.add(i);
recursion(res,tmp,k,n,sum+i,i+1);
tmp.remove(tmp.size()-1);
}
}
public List<List<Integer>> combinationSum3(int k, int n) {
List<List<Integer>> res = new ArrayList<>();
List<Integer> tmp = new ArrayList<>();
recursion(res, tmp, k, n, 0, 1);
return res;
}
}
3.leetcode39 组合总和
给你一个 无重复元素 的整数数组 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 。
仅有这两种组合。
class Solution {
public void recursion(List<List<Integer>> res, List<Integer> tmp, int[] candidates, int target, int sum, int index){
if(sum==target){
res.add(new ArrayList<>(tmp));
return;
}
for(int i=index;i<candidates.length;i++){
if(sum+candidates[i]>target) // 剪枝
break;
tmp.add(candidates[i]);
recursion(res, tmp, candidates, target, sum+candidates[i], i);// 因为可重复,所以从i开始
tmp.remove(tmp.size()-1);
}
}
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> res = new ArrayList<>();
List<Integer> tmp = new ArrayList<>();
Arrays.sort(candidates); // 需要排序
recursion(res,tmp,candidates,target,0,0);
return res;
}
}
4.leetcode40 组合总和ll
给定一个候选人编号的集合 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]
]
与上一题有两个区别:1.原数组中有重复元素 2.每个数字在每个组合中只能用一次
1问题用used数组处理(used数组判断使用过后continue) 2问题每次回溯使用i+1
class Solution {
public void recursion(List<List<Integer>> res, List<Integer> tmp, int[] candidates, int target, int sum, int index, boolean[] used){
if(sum==target){
res.add(new ArrayList<>(tmp));
return;
}
for(int i=index;i<candidates.length;i++){
if(sum+candidates[i]>target)
break;
if(i!=0 && candidates[i]==candidates[i-1] && used[i-1]==false)
continue;
used[i] = true;
tmp.add(candidates[i]);
recursion(res,tmp,candidates,target,sum+candidates[i],i+1, used);
tmp.remove(tmp.size()-1);
used[i] = false;
}
}
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
List<List<Integer>> res = new ArrayList<>();
List<Integer> tmp = new ArrayList<>();
Arrays.sort(candidates);
boolean[] used = new boolean[candidates.length];
Arrays.fill(used, false);
recursion(res,tmp,candidates,target,0,0,used);
return res;
}
}
5.leetcode17 电话号码的字母组合
给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。答案可以按 任意顺序 返回。
给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。
示例 1:
输入:digits = "23"
输出:["ad","ae","af","bd","be","bf","cd","ce","cf"]
示例 2:
输入:digits = ""
输出:[]
代码中的index和前几道题不同,代表的是遍历到digits中的第几个数字。
class Solution {
public void recursion(List<String> res, StringBuilder tmp, String digits, String[] nums, int index){
if(tmp.length()==digits.length()){
res.add(tmp.toString());
return;
}
String str = nums[digits.charAt(index)-'0'];
for(int i=0;i<str.length();i++){
tmp.append(str.charAt(i));
recursion(res,tmp,digits,nums,index+1);
tmp.deleteCharAt(tmp.length()-1);
}
}
public List<String> letterCombinations(String digits) {
if(digits==null || digits.length()==0)
return new ArrayList<>();
String[] nums = {"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
List<String> res = new ArrayList<>();
StringBuilder tmp = new StringBuilder();
recursion(res,tmp,digits,nums,0);
return res;
}
}
2.分割问题
1.leetcode131 分割回文串
给你一个字符串 s,请你将 s 分割成一些子串,使每个子串都是 回文串 。返回 s 所有可能的分割方案。
回文串 是正着读和反着读都一样的字符串。
示例 1:
输入:s = "aab"
输出:[["a","a","b"],["aa","b"]]
class Solution {
public boolean isPail(String s, int i, int j){
while(i<j){
if(s.charAt(i)==s.charAt(j)){
i++;
j--;
}else{
return false;
}
}
return true;
}
public void recursion(List<List<String>> res, List<String> tmp, String s, int index){
if(index==s.length()){
res.add(new ArrayList<>(tmp));
return;
}
for(int i=index;i<s.length();i++){
if(isPail(s,index,i)){
tmp.add(s.substring(index,i+1));
}else{
continue;
}
recursion(res,tmp,s,i+1);
tmp.remove(tmp.size()-1);
}
}
public List<List<String>> partition(String s) {
List<List<String>> res = new ArrayList<>();
List<String> tmp = new ArrayList<>();
recursion(res, tmp, s, 0);
return res;
}
}
2.leetcode93 复原ip地址
有效 IP 地址 正好由四个整数(每个整数位于 0 到 255 之间组成,且不能含有前导 0),整数之间用 '.' 分隔。
例如:"0.1.2.201" 和 "192.168.1.1" 是 有效 IP 地址,但是 "0.011.255.245"、"192.168.1.312" 和 "192.168@1.1" 是 无效 IP 地址。
给定一个只包含数字的字符串 s ,用以表示一个 IP 地址,返回所有可能的有效 IP 地址,这些地址可以通过在 s 中插入 '.' 来形成。你 不能 重新排序或删除 s 中的任何数字。你可以按 任何 顺序返回答案。
例 1:
输入:s = "25525511135"
输出:["255.255.11.135","255.255.111.35"]
class Solution {
public void recursion(List<String> res, StringBuilder tmp, String s, int index, int num){
if(index==s.length() && num==4){
res.add(tmp.toString());
return;
}
if(index==s.length()||num==4)
return;
for(int i=index;i<s.length() && i-index<3 && Integer.parseInt(s.substring(index,i+1))>=0 && Integer.parseInt(s.substring(index,i+1))<=255;i++){// ip段的长度最大为3
if(i+1-index>1 && s.charAt(index)-'0'==0)
continue;
tmp.append(s.substring(index, i+1));
if(num<3)
tmp.append(".");
recursion(res,tmp,s,i+1,num+1);
tmp.delete(index+num,i+num+2);
}
}
public List<String> restoreIpAddresses(String s) {
List<String> res = new ArrayList<>();
StringBuilder tmp = new StringBuilder();
recursion(res,tmp,s,0,0);
return res;
}
}
3.子集问题
子集问题相当于求决策树上的每个节点结果。所以递归时直接加入结果集。
1.leetcode78 子集
给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。
解集 不能 包含重复的子集。你可以按 任意顺序 返回解集。
示例 1:
输入:nums = [1,2,3]
输出:[[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]
class Solution {
public void recursion(List<List<Integer>> res, List<Integer> tmp, int[] nums, int index){
res.add(new ArrayList<Integer>(tmp)); // 直接加入结果集
if(tmp.size()>=nums.length) // 剪枝
return;
for(int i=index;i<nums.length;i++){
tmp.add(nums[i]);
recursion(res,tmp,nums,i+1);
tmp.remove(tmp.size()-1);
}
}
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
List<Integer> tmp = new ArrayList<>();
recursion(res,tmp,nums,0);
return res;
}
}
2.leetcode90 子集ll
给你一个整数数组 nums ,其中可能包含重复元素,请你返回该数组所有可能的子集(幂集)。
解集 不能 包含重复的子集。返回的解集中,子集可以按 任意顺序 排列。
示例 1:
输入:nums = [1,2,2]
输出:[[],[1],[1,2],[1,2,2],[2],[2,2]]
class Solution {
public void recursion(List<List<Integer>> res, List<Integer> tmp, int[] nums, int index, boolean[] used){
res.add(new ArrayList<Integer>(tmp));
if(tmp.size()>=nums.length)
return;
for(int i=index;i<nums.length;i++){
if(used[i])
continue;
if(i!=0 && nums[i]==nums[i-1] && used[i-1]==false)
continue;
used[i] = true;
tmp.add(nums[i]);
recursion(res,tmp,nums,i+1,used);
tmp.remove(tmp.size()-1);
used[i] = false;
}
}
public List<List<Integer>> subsetsWithDup(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
List<Integer> tmp = new ArrayList<>();
Arrays.sort(nums);
boolean[] used = new boolean[nums.length];
Arrays.fill(used, false);
recursion(res,tmp,nums,0,used);
return res;
}
}
4.排列问题
首先排列是有序的,也就是说 [1,2] 和 [2,1] 是两个集合,这和之前分析的子集以及组合所不同的地方。
1.不用使用index
2.每次循环从0开始
1. leetcode46 全排列
给定一个不含重复数字的数组 nums ,返回其 所有可能的全排列 。你可以 按任意顺序 返回答案。
示例 1:
输入:nums = [1,2,3]
输出:[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
class Solution {
public void recursion(List<List<Integer>> res, List<Integer> tmp, int[] nums, boolean[] used){
if(tmp.size()==nums.length){
res.add(new ArrayList<>(tmp));
return;
}
for(int i=0;i<nums.length;i++){
if(used[i])
continue;
tmp.add(nums[i]);
used[i] = true;
recursion(res,tmp,nums,used);
tmp.remove(tmp.size()-1);
used[i] = false;
}
}
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
List<Integer> tmp = new ArrayList<>();
boolean[] used = new boolean[nums.length];
Arrays.fill(used, false);
recursion(res,tmp,nums,used);
return res;
}
}
2. leetcode47 全排列ll
给定一个可包含重复数字的序列 nums ,按任意顺序 返回所有不重复的全排列。
示例 1:
输入:nums = [1,1,2]
输出:
[[1,1,2],
[1,2,1],
[2,1,1]]
class Solution {
public void recursion(List<List<Integer>> res, List<Integer> tmp, int[] nums, boolean[] used){
if(tmp.size()==nums.length){
res.add(new ArrayList<>(tmp));
return;
}
for(int i=0;i<nums.length;i++){
if(used[i])
continue;
if(i!=0 && nums[i]==nums[i-1] && used[i-1]==false)
continue;
tmp.add(nums[i]);
used[i] = true;
recursion(res,tmp,nums,used);
tmp.remove(tmp.size()-1);
used[i] = false;
}
}
public List<List<Integer>> permuteUnique(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
List<Integer> tmp = new ArrayList<>();
boolean[] used = new boolean[nums.length];
Arrays.fill(used, false);
Arrays.sort(nums);
recursion(res,tmp,nums,used);
return res;
}
}
3. 字符的全排列
给一个字符串,这个字符串里可能会包含重复的字母,让求这个字符串所有可能的排列情况数。
比如字符串"AAB",它的可能情况有A B AA AB BA AAB BAA ABA,要返回8;
public class Main1 {
// 方法1
// [A, AA, AAB, AB, ABA, B, BA, BAA]
public static void recursion(ArrayList<String> res, StringBuilder tmp, String str, int n, boolean[] used){
if(tmp.length()>0)
res.add(tmp.toString());
if(tmp.length()>n)
return;
for(int i=0;i<str.length();i++){
if(used[i])
continue;
if(i>0 && str.charAt(i)==str.charAt(i-1) && used[i-1]==false)
continue;
used[i] = true;
tmp.append(str.charAt(i));
recursion(res, tmp, str, n+1, used);
tmp.deleteCharAt(tmp.length()-1);
used[i] = false;
}
}
public static void main(String[] args){
String str = "AAB";
ArrayList<String> res = new ArrayList<>();
StringBuilder tmp = new StringBuilder();
boolean[] used = new boolean[str.length()];
Arrays.fill(used, false);
recursion(res, tmp, str, 0, used);
System.out.println(res);
return;
}
// 方法2
// [A, B, AA, AB, BA, AAB, ABA, BAA]
public static void recursion(ArrayList<String> res, StringBuilder tmp, String str, int n, boolean[] used){
if(tmp.length()==n){
res.add(tmp.toString());
return;
}
for(int i=0;i<str.length();i++){
if(used[i])
continue;
if(i>0 && str.charAt(i)==str.charAt(i-1) && used[i-1]==false)
continue;
used[i] = true;
tmp.append(str.charAt(i));
recursion(res, tmp, str, n, used);
tmp.deleteCharAt(tmp.length()-1);
used[i] = false;
}
}
public static void main(String[] args){
String str = "AAB";
ArrayList<String> res = new ArrayList<>();
StringBuilder tmp = new StringBuilder();
boolean[] used = new boolean[str.length()];
for(int i=1;i<=str.length();i++){
Arrays.fill(used, false);
recursion(res, tmp, str, i, used);
}
System.out.println(res);
return;
}
}
其他:
1.leetcode491 递增子序列
给你一个整数数组 nums ,找出并返回所有该数组中不同的递增子序列,递增子序列中 至少有两个元素 。你可以按 任意顺序 返回答案。
数组中可能含有重复元素,如出现两个整数相等,也可以视作递增序列的一种特殊情况。
示例 1:
输入:nums = [4,6,7,7]
输出:[[4,6],[4,6,7],[4,6,7,7],[4,7],[4,7,7],[6,7],[6,7,7],[7,7]]
该题有点像求子集,每个决策树节点上的值都作为结果
class Solution {
public void recursion(List<List<Integer>> res, List<Integer> tmp, int[] nums, int index){
if(tmp.size()>1){
res.add(new ArrayList<>(tmp));
}
int[] used = new int[201];
for(int i=index;i<nums.length; i++){
if(!tmp.isEmpty() && nums[i]<tmp.get(tmp.size()-1) || (used[nums[i]+100]==1))
continue;
used[nums[i]+100] = 1;
tmp.add(nums[i]);
recursion(res, tmp, nums, i+1);
tmp.remove(tmp.size()-1);
}
}
public List<List<Integer>> findSubsequences(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
List<Integer> tmp = new ArrayList<>();
recursion(res, tmp, nums, 0);
return res;
}
}
3.leetcode784 字母大小写全排列
给定一个字符串 s ,通过将字符串 s 中的每个字母转变大小写,我们可以获得一个新的字符串。
返回 所有可能得到的字符串集合 。以 任意顺序 返回输出。
示例 1:
输入:s = "a1b2"
输出:["a1b2", "a1B2", "A1b2", "A1B2"]
因为这道题可以在原数组上修改大小写,所以不需要循环,并且通过a^=32可以快速切换大小写。
class Solution {
public void recursion(List<String> res, char[] arr, int index){
if(index==arr.length){
res.add(new String(arr));
return;
}
recursion(res,arr,index+1);// 无论是数字还是字母先递归下一个字符
if(Character.isLetter(arr[index])){ // 当是字母的时候,转换大小写然后递归回溯
arr[index] ^= 32;
recursion(res, arr, index+1);
arr[index] ^= 32;
}
}
public List<String> letterCasePermutation(String s) {
List<String> res = new ArrayList<>();
recursion(res,s.toCharArray(),0);
return res;
}
}
总结下来:
- 组合类问题使用index,循环从index开始,每次递归index = i+1,当元素可以重复使用时index=i
- 集合类问题,相当于求决策树中每个节点的状态,所以每次递归直接加入结果集,不需要终止结果判断。
- 分割类问题和组合类问题类似,index代表要分割的位置。
- 排列类问题不使用index,循环从0开始,使用boolean[] used记录哪些元素被访问了。
无论哪种情况,当原数组有重复元素时,需要使用boolean[] used判断决策树当前行相同元素是否被访问过,而且要对原数组排序。
参考代码随想录