1 解题思想
这道题,就是第二个去全排列了,我昨天也预告过了,没看过的先看下上一题的解法:
Leetcode # 46. Permutations 全排列 解题报告
这道题有什么不一样的么?上一道题的数组是不重复的,这一次的是可以重复的。
但我们输出的时候,是不能输出重复排列的,那怎么办?
首先说明我这次的代码是基于上一次修改的。改进的方式是交换的那一个策略,所以你需要先去上一篇读一下这个具体的方式。
因为有重复,所以我们每次交换的时候,对于每一个取值,只交换一次!
什么意思,对于序列【0,1,2,2,3,3,3,4,4,4,4.。。】,当我指针在0上,需要和后面的进行一一交换,但因为存在重复,所以只和1个1交换,只和1个2交换,只和1个3交换!
而具体在实现的时候,我使用一个HashSet,保证交换的时候一个取值只交换一次
嗯,这不是结束。。全排列还有题。。不止这一个,后面我再介绍新的解法
2 原题
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], and [2,1,1].
3 AC解
public class Solution {
/**
* 这道题,其实好像用字典序也可以
* */
List<List<Integer>> list;
public List<Integer> toList(int nums[]){
List<Integer> list=new ArrayList<Integer>();
for(int i=0;i<nums.length;i++)
list.add(nums[i]);
return list;
}
public void swap(int[] nums,int a,int b){
int tmp=nums[a];
nums[a]=nums[b];
nums[b]=tmp;
}
public void dfs(int[] nums,int index){
if(index==nums.length)
list.add(toList(nums));
Set<Integer> set = new HashSet<Integer>(); //因为有重复,所以每次交换之和一个出现相同的元素进行交换,可以排序实现,我这里使用Set来表示
for(int i=index;i<nums.length;i++){
if(set.contains(nums[i]))
continue;
set.add(nums[i]);
swap(nums,i,index);
dfs(nums,index+1);
swap(nums,index,i);
}
}
//从第一个数开始,不停的与他之后的进行交换,中间有DFS
//这道题关键在于DFS 看具体的介绍
public List<List<Integer>> permuteUnique(int[] nums) {
// Arrays.sort(nums);
list=new ArrayList<List<Integer>>();
if(nums.length==0)
return list;
dfs(nums,0);
return list;
}
}