leetCode–全排列
全排列题目描述:
给定一个 没有重复 数字的序列,返回其所有可能的全排列。
示例:
输入: [1,2,3] 输出: [ [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1] ]
代码实现
import java.util.*;
/**
* @Date 2020/10/14 17:06
* @Version 10.21
* @Author DuanChaojie
*/
public class Solution {
public static void main(String[] args) {
}
/**
* 全排列问题-使用深度优先遍历
* @param nums 1 2 3
*/
public List<List<Integer>> permute(int[] nums){
// 获取数组的长度 3
int len = nums.length;
// 需要返回的结果集
List<List<Integer>> res = new ArrayList<List<Integer>>();
if (len == 0) {
// 如果数组长度为0,则返回空的res
return res;
}
// Stack JDK官方推荐我们使用Deque
Deque<Integer> path = new ArrayDeque<Integer>();
// 用来记录是否被使用过,默认 全为false
boolean[] used = new boolean[len];
// depth从0开始
dfs(nums,len,0,path,used,res);
// 返回深搜之后的结果
return res;
}
/**
* @param nums
* @param len
* @param depth
* @param path
* @param used
* @param res
*/
private void dfs(int[] nums, int len, int depth, Deque<Integer> path, boolean[] used, List<List<Integer>> res) {
if (depth == len){
// 深搜的终止条件
res.add(new ArrayList<>(path));
return;
}
// 遍历数组
for (int i = 0; i < len; i++) {
// 这一步很关键
if (used[i]){
continue;
}
// 如果还没有添加在path中,则添加在尾部
path.addLast(nums[i]);
// 并标记为true,即被使用过
used[i] = true;
dfs(nums,len,depth+1,path,used,res);
// 也不要忘了回溯
path.removeLast();
used[i] = false;
}
}
}