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