思路:回溯(树形结构上的深度优先遍历)
回溯算法的复杂度主要由递归树的节点个数决定,时间复杂度是指数级别的,本质上是一种遍历的算法!
回溯算法是用一份状态变量遍历整个状态空间的方法,只需要在合适的状态做一个保存即可。这种遍历相对于广度优先是节约空间的。
class Solution {
public List<List<Integer>> permute(int[] nums) {
//输入数组长度
int n = nums.length;
List<List<Integer>> res = new ArrayList<>();
if(n == 0){
return res;
}
Deque<Integer> path = new ArrayDeque<>();
boolean[] used = new boolean[n];
//0:当前已经选择了几个数
//path:从根节点到任意节点的列表,是一个栈
//used:bool数组,保存了当前的数是否被选择,初始化为false
dfs(nums,n,0,path,used,res);
return res;
}
//depth:表示当前递归到了第几层
private void dfs(int[] nums,int n,int depth,Deque<Integer> path,boolean[] used,List<List<Integer>> res){
//递归终止条件:当前递归层数等于数组长度,即所有元素都考虑完了,得到了一个排列
if(depth == n){
//将path添加到res中
res.add(new ArrayList<>(path));
return;
}
for(int i=0;i<n;i++){
//如果当前的数已经被使用了,跳过
if(used[i]){
continue;
}
//当前这个数没有被使用
path.addLast(nums[i]);
used[i] = true;
dfs(nums,n,depth+1,path,used,res);
path.removeLast();
used[i]=false;
}
}
}