1.Given A collection of numbers, return all possible permutations.
For example,
[1,2,3]
The following permutations:
[1,2,3]
,,,,, [1,3,2]
[2,1,3]
[2,3,1]
[3,1,2]
and [3,2,1]
.
2.
Given A collection of numbers that might contain duplicates, return all possible unique permutations.
For example,
[1,1,2]
The following unique permutations:
[1,1,2]
, [1,2,1]
, and [2,1,1]
.
Solution:dfs
1 2 3
12 13 21 23 32 31
123 132 213 231 321 312
PackageLeetcode2;ImportJava.util.*; Public classpermutations { Public StaticArraylist<arraylist<integer>> Permute (int[] num) {ArrayList<ArrayList<Integer>> res=NewArraylist<arraylist<integer>>(); ArrayList<Integer> mem =NewArraylist<integer>(); intDeep=0; intLength=num.length; Booleanvisit[]=New Boolean[length]; DFS (RES,MEM,DEEP,NUM,VISIT,LENGTH); returnRes; } Public Static voidDFS (arraylist<arraylist<integer>>Res, ArrayList<Integer> Mem,intDeepint[] num,Boolean[] Visit,intl) {//TODO auto-generated Method Stub if(deep==l) { if(!res.contains (NewArraylist<integer>(MEM))) {Res.add (NewArraylist<integer>(MEM)); } return; } if(deep<l) { for(inti=0;i<l;i++){ if(i>0 && num[i-1] = = Num[i] &&!visit[i-1]) Continue; if(!Visit[i]) {Mem.add (num[i]); Visit[i]=true; DFS (Res,mem,deep+1, num,visit,l); if(Mem.size () >0) {Mem.remove (mem.size ()-1); Visit[i]=false; } } } } if(deep>num.length)return; } Public Static voidMain (string[] args) {//TODO auto-generated Method Stub int[] a={1,2,3}; System.out.print (Permute (a)); }}
47.Permutations 1&2