Java实现全排列
回溯思想
1.将数组划分为前后两块,前面是出现的数字,后面是没出现的数字
2.first表示当前正在填写数字的位置
3.temp用来存放每一种排列形式,最后放到res中
class Solution {
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> res=new ArrayList<List<Integer>>();
List<Integer> temp=new ArrayList<>();
for(int num:nums){
temp.add(num);
}
int n=nums.length;
backtrack(n,res,temp,0);
return res;
}
public void backtrack(int n,List<List<Integer>> res,List<Integer> temp,int first){
if(first==n){
res.add(new ArrayList<Integer>(temp));
}
for(int i=first;i<n;i++){
Collections.swap(temp,first,i);
backtrack(n,res,temp,first+1);
Collections.swap(temp,first,i);
}
}
}