Title:
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] .
Test Instructions:
Given an integer collection, this collection may contain duplicates, returning all the existing and unique combinations.
Like what:
[1,1,2]The following combinations are owned:
[1,1,2], [1,2,1] , and [2,1,1] .
Algorithm Analysis:
the question and the question the permutations " very similar, the only difference is that in this topic, the collection of elements can appear duplicated. on the basis of the previous algorithm, when we enumerate the elements of the position I, to exchange the next J elements and I, we first guarantee that there are no elements in the [i...j-1] range that are the same as the position J. It is possible to perform sequential lookups each time a swap is required.
AC Code:
<span style= "FONT-SIZE:12PX;" >public class Solution {public arraylist<arraylist<integer>> permuteunique (int[] num) {ArrayList< arraylist<integer>> result = new arraylist<arraylist<integer>> ();p ermuteunique (num, 0, result); return result;} private static void Permuteunique (int[] num, int start, arraylist<arraylist<integer>> result) {if (Start > = num.length) {arraylist<integer> item = convertarraytolist (num); Result.add (item);} for (int j = start; J <= Num.length-1; j + +) {if (Containsduplicate (num, start, j)) {Swap (num, start, j);p Ermuteunique (n Um, start + 1, result); Swap (num, start, j);}}} private static void Swap (int[] A, int i, int j) {int temp = A[i];a[i] = a[j];a[j] = temp;} private static Arraylist<integer> convertarraytolist (int[] num) {arraylist<integer> item = new ArrayList <Integer> (); for (int h = 0; h < num.length; h++) Item.add (Num[h]); return item;} private static Boolean containsduplicate (int[] arr, int start, int end) {for (int i = start; I <= end-1; i++) {if (arr[i] = = Arr[end]) return false;} return true;}} </span>
Copyright NOTICE: This article is the original article of Bo Master, reprint annotated source
[Leetcode] [Java] Permutations II