首页 > 其他 > 详细

Permutations II

时间:2015-06-19 02:08:53      阅读:256      评论: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 {
    public List<List<Integer>> permuteUnique(int[] nums) {
    	List<List<Integer>> total = new ArrayList<List<Integer>>();
    	if (nums==null) {
    		return total;
    	}
    	Arrays.sort(nums);
    	boolean[] flag = new boolean[nums.length];
    	solve(nums, flag, new ArrayList<Integer>(), total);
    	return total;
    }

	private void solve(int[] nums, boolean[] flag,
			ArrayList<Integer> list, List<List<Integer>> total) {
		if (nums.length == list.size()) {
			total.add(list);
			return;
		}
    	for (int i = 0; i < nums.length; i++) {
    		if (flag[i]) {
    			continue;
    		}
    		if (i>0 && nums[i]==nums[i-1] && !flag[i-1]) {
    			continue;
    		}
    		flag[i] = true;
    		ArrayList<Integer> t = new ArrayList<Integer>(list);
    		t.add(nums[i]);
    		solve(nums, flag, t, total);
    		flag[i] = false;
    	}
	}
}

?

Permutations II

原文:http://hcx2013.iteye.com/blog/2220728

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