[Leetcode-java] Permutations II

Source: Internet
Author: User

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] .

Test instructions: As with I, the only difference between finding all permutations is that there will be duplicate numbers in the array

Ideas: Join visited to determine whether the location is selected, to avoid the selection of itself, but this will still be tle, then need the most critical step, start Dfs before the nums sort, so that when the DFS when nums[i] = = Nums[i-1] and visited[i-1] ==false words continue, imagine, at this time the number and the previous is the same, the previous one has not been visited to prove that the number of the arrangement has been completed that this number is definitely not used.

Code:

 Public classSolution { PublicList<list<integer>> Permuteunique (int[] nums) {List<List<Integer>> List =NewArraylist<list<integer>>(); if(Nums = =NULL|| Nums.length = = 0)            returnlist; List<Integer> temp =NewArraylist<integer>(); Boolean[] visited =New Boolean[Nums.length];   Arrays.sort (Nums); //Key 1DFS (list, temp, nums, visited, 0); returnlist; }         Public voidDFS (list<list<integer>> List, List<integer> temp,int[] Nums,Boolean[] visited,intcount) {        if(Count = =nums.length) {if(!list.contains (temp)) List.add (NewArraylist<integer>(temp)); return; }                 for(inti = 0; i < nums.length; i++) {            if(i > 0 && nums[i-1] = = Nums[i] &&!visited[i-1])//Key 2                Continue; if(Visited[i])Continue; Visited[i]=true;            Temp.add (Nums[i]); DFS (list, temp, nums, visited, Count+1); Temp.remove (Temp.size ()-1); Visited[i]=false; }    }}

[Leetcode-java] 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.