某个递归树如下:
由123集合中挑选出空,1,2,3,这个横向拆分的过程就是在进行for循环,最初index肯定是0,我们称这个为第一层。
for (int i = index; i < nums.length; i++) {}
而纵向往下的过程就是在递归,递归时也有横向的for循环,这时候就要控制for循环的起始点也就是index的起始值(大部分编程题就是在控制index的选择方式来控制递归树往预期的方向生成)。
1、index如果选择index+1,代表上一层的for循环每条分支往下一层走时都从固定的index+1开始,则不管横向for循环走到哪里,纵向看每一层所有分支对应的index的深度都相等。
所以如果上一层for循环到3了,index还在2,就会出现3,2的情况。
不进行其他操作时的递归树为:
index在1:1;2;3
index在2:12,13;22,23;32,33;
index在3:123,133;223,233;323,333
index在n:。。。。。。
适合要求结果集为等长且元素不重复的场景,如123求排列123,132,213,231,312,321等。
输入: [1,2,3]
输出:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]
class Solution {
List<List<Integer>> res = new ArrayList<>();
List<Integer> temp = new ArrayList<>();
public List<List<Integer>> permute(int[] nums) {
for (int num : nums) {
temp.add(num);
}
permute(nums.length, 0);
return res;
}
public void permute(int length, int index) {
// 递归结束条件,index走到temp最后一个元素,没有别的情况直接add
if (index == length - 1) {
res.add(new ArrayList<Integer>(temp));
return;
}
// 递归
for (int i = index; i < length; i++) {
// 把i对应元素和index对应元素互换
Collections.swap(temp, index, i);
permute(length, index + 1);
Collections.swap(temp, index, i);
// 把i对应元素和index对应元素互换
}
}
}
2、index如果选择index,index永远涨不了,相当于往下一层走时都可以从数组头部开始重新遍历。
不进行其他操作时的递归树为:
index在1:1;2;3
index在1:11,12,13;21,22,23;31,32,33
index在1:111,112,113;121,122,123;131,132,133;211,212,213;221,222,223;231,232,233;
311,312,313;321,322,323;331,332,333
index在n:。。。。。。
3、index如果选择i,上一层的for循环每条分支往下一层走时,可以重复上次for循环的分支停留的位置继续走
index在1:1;2;3
index在1:11,12,13;index在2:22,23;index在3:33
index在1:111,112,113;index在2:122,123;222,223;index在3:133,233,333
index在n:。。。。。。
适合求硬币问题的场景,每个硬币可以使用多次
输入:candidates = [2,3,6,7], target = 7,
所求解集为:
[
[7],
[2,2,3]
]
public class Solution {
List<List<Integer>> res = new ArrayList<>();
Deque<Integer> path = new LinkedList<>();
public List<List<Integer>> combinationSum(int[] candidates, int target) {
if (candidates.length == 0) {
return res;
}
Arrays.sort(candidates);
dfs(candidates, 0, target);
return res;
}
private void dfs(int[] candidates, int index, int target) {
if (target == 0) {
res.add(new ArrayList<>(path));
return;
}
for (int i = index; i < candidates.length; i++) {
if (candidates[i] > target) {
break;
}
path.addLast(candidates[i]);
// 由于每一个元素可以重复使用,下一轮搜索的起点依然是 i
dfs(candidates, i, target - candidates[i]);
path.removeLast();
}
}
}
4、index如果选择i+1,上一层的for循环每条分支往下一层走时,接着上次for循环的分支停留的位置往后继续走
index在1:1;2;3
index在2:12,13;index在3:23
index在3:123;
index在n:。。。。。。
适合当前求子集的场景。
输入: nums = [1,2,3]
输出:
[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]
class Solution {
List<List<Integer>> res = new ArrayList<>();
List<Integer> temp = new ArrayList<>();
public List<List<Integer>> subsets(int[] nums) {
backtrack(0, nums);
return res;
}
public void backtrack(int index, int[] nums) {
res.add(new ArrayList<>(temp));
for (int i = index; i < nums.length; i++) {
temp.add(nums[i]);
backtrack(i + 1, nums);
temp.remove(temp.size() - 1);
}
}
}