Topic
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]
.
Resolution
Test instructions: To find an array of all permutations, unlike the "leetcode" permutations problem solving report, the number in the array is duplicated.
For the whole arrangement, now more commonly used algorithms are based on "Leetcode" Next permutation problem solving report from small to large to find out all the permutations.
Algorithm: Backtracking, dictionary ordering method.
public class Solution {list<list<integer>> ans = new arraylist<list<integer>> (); Public list<list<integer>> permuteunique (int[] num) {arrays.sort (num); The original array must first be added to the result set list<integer> List = new arraylist<integer> (); for (int x:num) {list.add (x); } ans.add (list); Add the next solution individually for (int i = 1; i < factorial (num.length); i++) {nextpermutation (num); } return ans; } public void Nextpermutation (int[] num) {//find last positive sequence int i = num.length-1; while (i > 0 && num[i] <= num[i-1]) {i--; } if (i <= 0) return; Find the last number larger than num[i-1] int j = num.length-1; while (J >= i && Num[j] <= num[i-1]) {j--; }//Exchange int tmp = NUM[I-1]; NUM[I-1] = Num[j]; NuM[J] = tmp; Inverse row i-1 After the number of int l = i, r = num.length-1; while (L < r) {tmp = Num[l]; NUM[L] = Num[r]; NUM[R] = tmp; l++; r--; }//Added to result set list<integer> List = new arraylist<integer> (); for (int x:num) {list.add (x); } ans.add (list); } public int factorial (int n) {return n = = 0? 1:n * factorial (n-1); }}
Related topics: "Leetcode" permutations Problem solving report and "Leetcode" Next permutation problem solving report
"Leetcode" permutations II problem Solving report