给定一个 没有重复 数字的序列,返回其所有可能的全排列。
输入: [1,2,3]
输出:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]
采用回溯法的方式来解决
class Solution {
public List<List<Integer>> permute(int[] nums) {
ArrayList<List<Integer>> al = new ArrayList<List<Integer>>();
boolean [] path = new boolean[nums.length];
int frist = 0;
ArrayList<Integer> subal = new ArrayList<Integer>();
dfs(nums,path,al,subal,frist);
return al;
}
public void dfs(int[] nums,boolean[] path,ArrayList<List<Integer>> al,ArrayList<Integer> subal ,int frist) {
if(frist == nums.length){
al.add(new ArrayList<Integer>(subal));
return;
}
for(int i = 0;i<nums.length;i++){
if(!path[i]){
subal.add(nums[i]);
path[i] = true;
dfs(nums,path,al,subal,frist+1);
subal.remove(subal.size()-1);
path[i] = false;
}
}
}
}