LeetCode|Permutations II

题目

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].

思路

这道题跟Permutations的具体差别就是怎么去掉重复的.

思路如下

我们先排序,然后在递归之前进行消除重复数字的操作。但是这样做还是得不到正确的答案。因为当你交换数字的时候,可能会使后面的数字又无序了.解决方法就是用一个临时数组保存当前的结果,然后对求解数组再次排序,递归回来后在重新赋值就可以了额...

这道题还是卡住了我...LZ果断需要刷刷题啊

代码

public class Solution {
	public void swap(int[] a,int p1,int p2)
	{
		int temp = a[p1];		
		a[p1] = a[p2];
		a[p2] = temp;
	}
	
	public void Permutations(int[] num ,int begin, int end, ArrayList<ArrayList<Integer>> result )
	{
		if(begin>end)
		{
			ArrayList<Integer> temp = new ArrayList<Integer>();
			for(int i = 0 ;i <= end; i ++)
			{
				temp.add(num[i]);
			}
			result.add(temp);
		}
		else
		{			
			for(int i = begin; i <=end ; i++)
			{
				int[] temp = Arrays.copyOf(num, num.length);
				Arrays.sort(num, begin, end+1);
				if(begin!=i&&num[i]==num[i-1])
				{
					continue;
				}
				swap(num,begin,i);
				Permutations(num,begin+1,end,result);
				num = Arrays.copyOf(temp, temp.length);
				swap(num,begin,i);

			}
		}
	}
	
	public boolean isCome (int[] num,int begin,int end)
	{
		for(int i = begin;i<end;i++)
		{
			if(num[begin]==num[end])
				return true;
		}
		return false;
	}
	
    public  ArrayList<ArrayList<Integer>> permuteUnique(int[] num)
    {
        ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();       
        if( num.length == 0 )
        	return result;
        Arrays.sort(num);
        
        Permutations(num,0,num.length-1,result);
        return result;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值