码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode][I]Permutations II

时间:2014-09-23 17:07:24      阅读:222      评论:0      收藏:0      [点我收藏+]

标签:java   leetcode   

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

标签:java   leetcode   

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

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