首页 > 其他 > 详细

[LeetCode][I]Permutations II

时间:2014-09-23 15:25:15      阅读:221      评论: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].

public class Solution {
	boolean isUsed[];
	List<List<Integer>> result;
	List<Integer> list;

	public List<List<Integer>> permuteUnique(int[] num) {
		isUsed = new boolean[num.length];
		result = new ArrayList<List<Integer>>();
		list = new ArrayList<Integer>();
		Arrays.sort(num);
		permute(num);
		return result;

	}

	private void permute(int[] num) {
		if (list.size() == num.length) {
			result.add(new ArrayList<Integer>(list));
			return;
		}

		for (int i = 0; i < num.length; i++) {
			if (isUsed[i])
				continue;
			if (i > 0 && num[i - 1] == num[i] && (!isUsed[i - 1]))
				continue;
			isUsed[i] = true;
			list.add(num[i]);
			permute(num);
			list.remove(list.size() - 1);
			isUsed[i] = false;
		}
	}
}





[LeetCode][I]Permutations II

原文:http://blog.csdn.net/guorudi/article/details/39497023

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