[LeetCode] Permutations II solution report, permutationⅱ
[Question]
Given a collection of numbers that might contain duplicates, return all possible unique permutations.
For example,
[1,1,2]Have the following unique permutations:
[1,1,2],[1,2,1], And[2,1,1].
[Resolution]
Question: Find the full arrangement of an array. Different from the [LeetCode] Permutations solution Report, the number in the array is repeated.
For full sorting, the commonly used algorithm is to find all the sorting items one by one based on the [LeetCode] Next Permutation problem solving report from small to large.
Algorithms: backtracking and lexicographical order.
Public class Solution {List <Integer> ans = new ArrayList <List <Integer> (); public List <Integer> permuteUnique (int [] num) {Arrays. sort (num); // you must first add the original array to the result set List <Integer> list = new ArrayList <Integer> (); for (int x: num) {list. add (x);} ans. add (list); // One by one add the next solution for (int I = 1; I <factorial (num. length); I ++) {nextPermutation (num);} return ans;} public void nextPermutation (int [] Num) {// locate the last positive 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; // The number int l = I, r = num after the inverse I-1. length-1; while (l <r) {tmp = num [l]; num [l] = num [r]; num [r] = tmp; l ++; r --;} // Add to result set List <Intege R> 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 Questions: [LeetCode] Permutations solution report and [LeetCode] Next Permutation solution report