题解 | #没有重复项数字的全排列#
没有重复项数字的全排列
http://www.nowcoder.com/practice/4bcf3081067a4d028f95acee3ddcd2b1
import java.util.*;
public class Solution {
ArrayList<ArrayList<Integer>> ans ;
public ArrayList<ArrayList<Integer>> permute(int[] num) {
for(int i = 0;i<num.length;i++){
list.add(num[i]);
callBack(list,0,new ArrayList<>());
return ans;
path.add(list.get(index));
ans.add(new ArrayList<>(path));
path.remove(list.get(index));
return;
Collections.swap(list,index,i);
path.add(list.get(index));
callBack(list,index+1,path);
path.remove(list.get(index));
Collections.swap(list,index,i);
}
}
}
public class Solution {
ArrayList<ArrayList<Integer>> ans ;
public ArrayList<ArrayList<Integer>> permute(int[] num) {
ans = new ArrayList<>();
//将数组转化为集合
ArrayList<Integer> list = new ArrayList<>();for(int i = 0;i<num.length;i++){
list.add(num[i]);
}
return ans;
}
//回溯
public void callBack(ArrayList<Integer> list,int index ,ArrayList<Integer> path){
//最后一个下标时加入路径集合,加入到结果集合中
if(index == list.size()-1){path.add(list.get(index));
ans.add(new ArrayList<>(path));
path.remove(list.get(index));
return;
}
//遍历
for(int i = index;i<list.size();i++){Collections.swap(list,index,i);
path.add(list.get(index));
callBack(list,index+1,path);
path.remove(list.get(index));
Collections.swap(list,index,i);
}
}
}