[LeetCode] Permutations II solution report, permutationⅱ

Source: Internet
Author: User

[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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.