Leetcode 47 PermutationsII 全排列2,给定的几个数字是重复的,输出他们所有的排列

刚开始还觉得和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));
	}

}

哈哈

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值