思路
不需要剪枝的回溯算法,照模板写即可
代码
private List<List<Integer>> res =new ArrayList<>();
public List<List<Integer>> permute(int[] nums) {
if(nums.length==0)
return res;
boolean[] choice=new boolean[nums.length];
List<Integer> path= new ArrayList<>();
backtrack(choice,0,path,nums);
return res;
}
public void backtrack(boolean[] choice,int index,List<Integer> path,int[] nums) {
if(index==nums.length) {
res.add(new ArrayList<>(path));//这里不能直接添加path,不明白原理
return;
}
for(int i=0;i<nums.length;i++) {
if(!choice[i]) {
path.add(nums[i]);
choice[i]=true;
backtrack(choice,index+1,path,nums);
choice[i]=false;
path.remove(path.size()-1);
}
}
}