Problem Description: Given an array, there are repeating elements in the array, perfection arranged.
Algorithm analysis: As with the previous problem, just to go heavy.
3 Importjava.util.ArrayList;4 ImportJava.util.HashSet;5 Importjava.util.List;6 ImportJava.util.Set;7 8 Public classPermutationsunique {9 PublicArraylist<arraylist<integer>> Permuteunique (int[] num) {Tenarraylist<arraylist<integer>> result =NewArraylist<arraylist<integer>>(); OnePermuteunique (num, 0, result); A returnresult; - } - the Private voidPermuteunique (int[] num,intStart, arraylist<arraylist<integer>>result) { - - if(Start >=num.length) { -arraylist<integer> item =convertarraytolist (num); + Result.add (item); - } + A for(intj = start; J < Num.length; J + +) { at if(containsduplicate (num, start, j)) { - swap (num, start, j); -Permuteunique (num, start + 1, result); - swap (num, start, j); - } - } in } - to PrivateArraylist<integer> Convertarraytolist (int[] num) { +arraylist<integer> item =NewArraylist<integer>(); - for(inth = 0; H < num.length; h++) { the Item.add (Num[h]); * } $ returnitem;Panax Notoginseng } - //Nums[start] and Nums[end] exchange, if start-end between nums[i]==nums[end], it means that it has been exchanged before, there is no need to repeat. the Private BooleanContainsduplicate (int[] arr,intStartintend) { + for(inti = start; I < end; i++) { A if(Arr[i] = =Arr[end]) { the return false; + } - } $ return true; $ } - - Private voidSwapint[] A,intIintj) { the inttemp =A[i]; -A[i] =A[j];WuyiA[J] =temp; the } - Wu - About $ //This method is the same as permutation, because the set is used, so it has gone heavy. - Public StaticList<list<integer>> PermuteUnique2 (int[] num) { -list<list<integer>> returnlist =NewArraylist<>(); -Returnlist.add (NewArraylist<integer>()); A + for(inti = 0; i < num.length; i++) { theSet<arraylist<integer>> Currentset =NewHashset<>(); - for(list<integer>l:returnlist) { $ for(intj = 0; J < L.size () + 1; J + +) { the L.add (J, Num[i]); theArraylist<integer> T =NewArraylist<integer>(l); the L.remove (j); the Currentset.add (T); - } in } theReturnlist =NewArraylist<>(currentset); the } About the returnreturnlist; the } the + Public Static voidMain (string[] args) - { thePermutations pt =Newpermutations ();Bayi int[] num = {1,2,1,3}; the System.out.println (Pt.permute (num). Size ()); the System.out.println (Pt.permute (num)); - } -}
Permutationsunique, perfection, go heavy.