46.全排序I
给定一个不含重复数字的数组 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]]
提示:
1 <= nums.length <= 6
-10 <= nums[i] <= 10
nums 中的所有整数 互不相同
思路
首先应该看出来他是为了得到问题的所有解,顾名思义,应当使用回溯法。回溯法也叫暴力法,不仅能得到问题的所有解,也能得到问题的最优解。
用[1,2,3]举例,
首次选择 1 剩余 [2,3]…
首次选择2 剩余 [1,3]
…
递归回溯问题
- 递归终止条件 需要 当前递归的深度depth和num的长度length
- 回溯需要知道是否使用了该数 使用Used数组 默认全为false 未使用
实现
package 力扣;
import java.util.ArrayList;
import java.util.List;
public class leetcode46 {
public static void main(String[] args) {
int[] nums ={1,2,3};
permute(nums);
}
public static List<List<Integer>> permute(int[] nums) {
int length = nums.length;
int depth=0;
boolean[] used=new boolean[length];
List<List<Integer>> res = new ArrayList<>();
List<Integer> path=new ArrayList<>();
DFS(nums,length,depth,res,path,used);
System.out.println(res);
return res;
}
private static void DFS(int[] nums, int length, int depth, List<List<Integer>> res, List<Integer> path, boolean[] used) {
// 递归终止条件
if(depth==length){
res.add(new ArrayList<>(path));
return;
}
for (int i = 0; i < length; i++) {
if(used[i]==false){
path.add(nums[i]);
used[i]=true;
System.out.println("递归结束前"+path);
DFS(nums,length,depth+1,res,path,used);
System.out.println("递归结束后"+path);
path.remove(depth);
used[i]=false;
}
}
}
}