Given a collection of numbers, return all possible permutations.
For example,[1,2,3] have the following permutations:[1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], and [3,2,1].DFS的题, 感觉有点像是八皇后问题的变形。 程序的框架和思想也差不多。
public class Solution { public ArrayList> permute(int[] num) { ArrayList > result = new ArrayList >(); permute(num,0,result); return result; } public void swap(int[] num,int a,int b){ int tp = num[a]; num[a] = num[b]; num[b] = tp; } public void permute(int[] num, int level, ArrayList > result) { int length = num.length; if(level==length){ ArrayList current= new ArrayList (); for(int el:num){ current.add(el); } result.add(current); }else{ permute(num,level+1,result); for(int i=level+1;i