Given a list of numbers with duplicate number in it. Find all unique permutations.
Example
For numbers [1,2,2]
the unique permutations are:
[
[1,2,2],
[2,1,2],
[2,2,1]
]
Challenge
Using recursion to do it is acceptable. If you can do it without recursion, that would be great!
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; ArrayList<Integer> line = new ArrayList<Integer>(); boolean[] visited = new boolean[nums.size()]; Collections.sort(nums); helper(result, line, visited, nums); return result; } public void helper(ArrayList<ArrayList<Integer>> result, ArrayList<Integer> line, boolean[] visited, ArrayList<Integer> nums){ if(line.size() == nums.size()){ result.add(new ArrayList<Integer>(line)); return; } for(int i = 0; i < nums.size(); i++){ if(visited[i]) continue; else if(i > 0 && nums.get(i) == nums.get(i - 1) && !visited[i - 1]) continue; line.add(nums.get(i)); visited[i] = true; helper(result, line, visited, nums); line.remove(line.size() - 1); visited[i] = false; } return; } }
时间: 2024-11-04 09:35:39