一、题目
给定一个不含重复数字的数组 nums
,返回其 所有可能的全排列 。你可以 按任意顺序 返回答案。
二、实现
class Solution {
public List<List<Integer>> permute(int[] nums) {
// 1.结果集
List<List<Integer>> res = new ArrayList<>();
// 2. 定义相关的变量,进行全排列
int len = nums.length;
if(len == 0) return res;
boolean v[] = new boolean[len]; //记录每个数字是否选择
List<Integer> path = new ArrayList<>(); //访问路径
dfs(nums, len, 0, path, v, res); //全排列
return res;
}
// n:数组中的元素总树; depth:当前排列中以后的数字个数
public void dfs(int[] nums, int n, int depth, List<Integer> path ,boolean v[], List<List<Integer>> res){
//1. 当前全排列中有n个数字(已完成一个排列)
if(depth == n){
res.add(new ArrayList(path));
}
//2. 依次将未选择的数字,作为下一层的元素
for(int i=0;i<n;i++){
if(!v[i]){
path.add(nums[i]);
v[i] = true;
dfs(nums,n,depth+1,path, v,res); //继续获取当前排列下一层的数字
path.remove(path.size()-1); //回溯
v[i] = false;
}
}
}
}