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]
]
递归。和前面的差不多,但维护一个boolean[] isVisited数组以保证同一数字前后顺序唯一。当前面的2还没有使用的时候,就不应该让后面的2使用。
切记同元素问题处理要先sort!因为如果判断前后相同那要先把它们聚拢在一起。
public class Solution { /* * @param nums: A list of integers * @return: A list of unique permutations */ public List<List<Integer>> permuteUnique(int[] nums) { // write your code here List<List<Integer>> result = new ArrayList<List<Integer>>(); if (nums == null){ return null; } if (nums.length == 0){ result.add(new ArrayList<Integer>()); return result; } boolean[] isVisited = new boolean[nums.length]; //切记要先sort!!!不然下面判断相邻的相同就不对了 Arrays.sort(nums); helper(new ArrayList<Integer>(), isVisited, nums, result); return result; } private void helper(List<Integer> current, boolean[] isVisited, int[] nums, List<List<Integer>> result){ if(current.size() == nums.length){ result.add(new ArrayList<Integer>(current)); } for(int i = 0; i < nums.length; ++i){ if(isVisited[i] || (i > 0 && nums[i] == nums[i - 1] && !isVisited [i - 1])){ continue; } isVisited[i] = true; current.add(nums[i]); helper(current, isVisited, nums, result); current.remove(current.size() - 1); isVisited[i] = false; } } }
时间: 2024-10-27 00:16:04