码迷,mamicode.com
首页 > 编程语言 > 详细

[LeetCode][Java] Permutations II

时间:2015-07-14 13:39:54      阅读:180      评论:0      收藏:0      [点我收藏+]

标签:leetcode   java   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].

题意:

给定一个整数集合,这个集合可能包含重复,返回所有的存在且唯一的组合。

比如:

[1,1,2] 拥有下面的这些组合:

[1,1,2][1,2,1], and [2,1,1].

算法分析:

这个题跟题目Permutations》非常类似,唯一的区别就是在这个题目中元素集合可以出现重复。在上一个算法的基础上,当我们枚举第i个位置的元素时,若要把后面第j个元素和i交换,则先要保证[i…j-1]范围内没有和位置j相同的元素。可行的做法是:可以每次在需要交换时进行顺序查找。

AC代码:

<span style="font-size:12px;">public class Solution 
{
	
	public ArrayList<ArrayList<Integer>> permuteUnique(int[] num) 
	{
		ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
		permuteUnique(num, 0, result);
		return result;
	}
	private static void permuteUnique(int[] num, int start, ArrayList<ArrayList<Integer>> result) 
	{
		if (start >= num.length ) 
		{
			ArrayList<Integer> item = convertArrayToList(num);
			result.add(item);
		}
		for (int j = start; j <= num.length-1; j++) 
		{
			if (containsDuplicate(num, start, j)) 
			{
				swap(num, start, j);
				permuteUnique(num, start + 1, result);
				swap(num, start, j);
			}
		}
	}
	private static void swap(int[] a, int i, int j)
	{
		int temp = a[i];
		a[i] = a[j];
		a[j] = temp;
	}
	private static ArrayList<Integer> convertArrayToList(int[] num) 
	{
		ArrayList<Integer> item = new ArrayList<Integer>();
		for (int h = 0; h < num.length; h++)
			item.add(num[h]);
		return item;
	}
	private static boolean containsDuplicate(int[] arr, int start, int end) 
	{
		for (int i = start; i <= end-1; i++) 
		{
			if (arr[i] == arr[end]) 
				return false;
		}
		return true;
	}
}</span>



版权声明:本文为博主原创文章,转载注明出处

[LeetCode][Java] Permutations II

标签:leetcode   java   permutations ii   

原文地址:http://blog.csdn.net/evan123mg/article/details/46875957

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!