import java.util.*;
public class Solution {
//全局变量:
ArrayList<ArrayList<Integer>> ret;
ArrayList<Integer> path ; //记录走过的路径
boolean[] check ;//检查该数子是否被选过。避免11的情况
public ArrayList<ArrayList<Integer>> permute (int[] num) {
ret = new ArrayList<ArrayList<Integer>>();
path = new ArrayList<Integer>();
check = new boolean[num.length];
dfc(num);
return ret;
}
//递归求解
public void dfc(int[] num){
//终止条件:全部遍历
if(num.length==path.size()){
//加入时需要new,不能直接加入,类中只是声明
ret.add(new ArrayList<>(path));
return;
}
//遍历数组进行决策
for(int i=0;i<num.length;i++){
//没走过时进行
if(check[i]==false){
//加入路径,修改check
path.add(num[i]);
check[i] = true;
//进行下一层决策
dfc(num);
//到最后一个节点回溯
//将当前节点设为未走过
check[i] = false;
//移除走的路径最后一个节点
path.remove(path.size()-1);
}
}
}
}