刚开始还觉得和90题蛮像的,但还是不一样的,受到46题的影响很容易走偏,其实人家就是简单的要活着不要,还有认为的加上规则,对于重复的数字,原本后面的一定要在原本前面的后面,对于重复的不能换位置。
题目:
Given a collection of numbers that might contain duplicates, return all possible unique permutations.
Example:
Input: [1,1,2] Output: [ [1,1,2], [1,2,1], [2,1,1] ]
我的较笨的解决办法:
package test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class LC47Try1
{
public List<List<Integer>> permuteUnique(int[] nums)
{
List<List<Integer>> ret = new ArrayList<List<Integer>>();
Arrays.sort(nums);
List<Integer> temp = new ArrayList<Integer>();
pass(nums, ret, temp, 0);
return ret;
}
public void pass(int[] nums,List<List<Integer>> ret,List<Integer> temp,int index){
if(index==nums.length){
if(!ret.contains(temp)){
ret.add(new ArrayList<Integer>(temp));
}
return;
}
for(int i=0;i<=index;i++){
if(i!=index){
if(temp.get(i)==nums[index]){
continue;
}
}
temp.add (i, nums[index]);
pass(nums, ret, temp, index+1);
temp.remove (i);
}
}
public static void main(String[] args)
{
LC47Try1 t = new LC47Try1();
int[] nums={2,2,1,1};
System.out.println(t.permuteUnique(nums));
}
}
上面的方法是用的46的办法,但是思路走偏了,看下面这个:
package test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class LC47Try2
{
public List<List<Integer>> permuteUnique(int[] nums)
{
List<List<Integer>> ret = new ArrayList<List<Integer>>();
//一般重复都会排序的
Arrays.sort(nums);
boolean[] tag = new boolean[nums.length];
List<Integer> temp = new ArrayList<Integer>();
pass(nums, ret, temp, tag);
return ret;
}
public void pass(int[] nums,List<List<Integer>> ret,List<Integer> temp,boolean[] tag){
if(temp.size()==nums.length){
ret.add(new ArrayList<Integer>(temp));
return;
}
for(int i=0;i<nums.length;i++){
if(tag[i]){
continue;
}
//tag[i-1]==false 保证后来的一定用在前一个的后面,这就是规则。亮点呀
if(i>0&&nums[i-1]==nums[i] && tag[i-1]==false ){
continue;
}
tag[i]=true;
temp.add(nums[i]);
pass(nums,ret,temp,tag);
tag[i]=false;
temp.remove(temp.size()-1);
}
}
public static void main(String[] args)
{
LC47Try2 t = new LC47Try2();
int[] nums={2,2,1,1};
System.out.println(t.permuteUnique(nums));
}
}
哈哈