首页 > 其他 > 详细

LeetCode|Permutations II

时间:2014-04-21 04:17:59      阅读:500      评论:0      收藏:0      [点我收藏+]

题目

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;
    }
}


LeetCode|Permutations II,布布扣,bubuko.com

LeetCode|Permutations II

原文:http://blog.csdn.net/hwb1992/article/details/24194811

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!