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

思路,使用字典序法,与http://blog.csdn.net/mlweixiao/article/details/38897499 代码除了函数名换了以外,没有任何改动
public class Solution {
	private void nextPermutation(int[] num) {
		int i;
		int cur = -1;
		int temp;
		// find the last increase sequence
		for (i = num.length - 1; i >= 1; i--) {
			if (num[i] > num[i - 1]) {
				cur = i - 1;
				break;
			}
		}

		// if the increase sequence exists,
		//swap the cur and the last one(bigger than it)
		if (cur != -1) {
			for (i = num.length - 1; i > cur; i--) {
				if (num[i] > num[cur]) {
					temp = num[cur];
					num[cur] = num[i];
					num[i] = temp;
					break;
				}
			}
		}
		
		for (i = cur + 1; 2 * i <= cur + num.length - 1; i++) {
			temp=num[i];
			num[i]=num[num.length-i+cur];
			num[num.length-i+cur]=temp;
		}
	}
	
    @SuppressWarnings({ "rawtypes", "unchecked" })
	public List<List<Integer>> permuteUnique(int[] num) {
		
    	
		Arrays.sort(num);
		int [] temparray=new int [num.length];
		System.arraycopy(num, 0, temparray, 0, num.length);
		
		ArrayList<List<Integer>> result = new ArrayList<List<Integer>>();
		
		for(;;){
			// 注意不能使用list.addAll(Arrays.asList(num));
			// 也不能使用Collection.addAll(list ,num);
			// Arrays.asList() 返回java.util.Arrays$ArrayList,
			// 而不是ArrayList。Arrays$ArrayList和ArrayList都是继承AbstractList,
			//remove,add等method在AbstractList中是默认throw
			// UnsupportedOperationException而且不作任何操作。
			
			//最根本的的原因是num是int [] 并非Integer []
			List list = new ArrayList<Integer>();
			for(int i=0;i<num.length;i++){
				list.add(num[i]);
			}
			result.add(list);
			nextPermutation(num);
			if(Arrays.equals(num, temparray)) break;
		}
		return result;        
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值