leetcode 47 Permutations II ----- java

Given a collection of numbers that might contain duplicates, return all possible unique permutations.

For example,
[1,1,2] have the following unique permutations:

[
  [1,1,2],
  [1,2,1],
  [2,1,1]
]

题目和上一道很类似,区别在于,上一道题的数组中的数都是不一样的,这道题有一样的。

首先套用了上一道题的最佳解法,想了两个解决方案:(见上一题解答)

一、最后result.add时,判断result中是否存在,简单,但是耗时较多, 最终超时。

二、将数组排序,然后每次置换数字的时候,判断是否已经换过,但是这里就出现了一个问题,本来排序好的数组在判断的时候只需要判断前一位是否已经使用过就可以了,但是由于会将nums数组的数字换位置,导致了每次换位置都可能使得数组乱序,导致无法做出最终答案,最后已失败告终。

然后就使用递归,比较简单。耗时3ms。

public class Solution {
    public List<List<Integer>> permuteUnique(int[] nums) {
		List<List<Integer>> result = new ArrayList<List<Integer>>();
		if (nums.length == 0)
			return null;
		Arrays.sort(nums);
		getResult(result,nums,new ArrayList<Integer>(),0,new int[nums.length]);
		return result;
	}

	public static void getResult(List<List<Integer>> result,int[] nums,List<Integer> ans,int num,int[] pos){
		if( num == nums.length){
			result.add(new ArrayList<Integer>(ans));
			return ;
		}
		for( int i = 0 ; i<nums.length;i++){
			if( pos[i] == 0 ){
				ans.add(nums[i]);
				pos[i] = 1;
				getResult(result,nums,ans,num+1,pos);
				pos[i] = 0;
				ans.remove(num);
				while(i<nums.length-1 && nums[i] == nums[i+1]){//在这里判断之后的数字是否一样,如果一样,就直接跳过。
				   i++;
				}
			}
		}
	}
}
 
原文地址:https://www.cnblogs.com/xiaoba1203/p/5695642.html