Lintcode:permutations II

Source: Internet
Author: User

Import Java.util.collections;class Solution {/** * @param nums:a list of integers.     * @return: A list of unique permutations. */Public arraylist<arraylist<integer>> Permuteunique (arraylist<integer> nums) {//write your        code here arraylist<arraylist<integer>> result = new arraylist<arraylist<integer>> ();        if (nums = = NULL | | nums.size () = = 0) {return result;        } collections.sort (Nums);        Boolean[] visited = new Boolean[nums.size ()];        arraylist<integer> list = new arraylist<integer> ();        Permutationhelper (result, list, nums, visited);    return result; } private void Permutationhelper (arraylist<arraylist<integer>> result, arraylist<integer> list, A Rraylist<integer> Nums, boolean[] visited) {if (list.size () = = Nums.size ()) {Result.add (new Arra            Ylist<integer> (list));        Return  }              for (int i = 0; i < nums.size (); i++) {if (visited[i] = = True | | (I! = 0 && nums.get (i) = = Nums.get (i-1) && visited[i-1] = false))            {continue;            } Visited[i] = true;            List.add (Nums.get (i));            Permutationhelper (result, list, nums, visited);            List.remove (List.size ()-1);        Visited[i] = false; }    }}

Use visited array to record which is accessed, visited[i-1] = = False very tricky, there may be 1222 ... In this case, with the second 2 recursion, the front of the 2 should be not yet visited, so this time visited[i-1] = = False.

Lintcode:permutations II

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.