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],
  [2,1,1]
]

思路:与Permutations类似,这回是有重复元素,所以对于1,2,1来说1,2,1与1,2,1中1作为第一次递归入口的结果是重复的,为了避免重复,不能让两个1都为递归入口,所以先排序,变成1,1,2,当第一个1已经作为过本次递归的入口时,下个1就不能作为本次递归的入口。由于有重复元素,所以不能像之前那样用arraylist.contains判断是否使用过,而是用一个额外的数组存储使用信息。

public class Solution {
    public List<List<Integer>> permuteUnique(int[] nums) {
		Arrays.sort(nums);
		List<List<Integer>> list = new ArrayList<List<Integer>>();
		boolean[] used = new boolean[nums.length];
		List<Integer> l = new ArrayList<Integer>();
		dfs(list, l, nums, used);
		return list;
	}

	public void dfs(List<List<Integer>> List, List<Integer> l, int[] nums, boolean[] used) {
		if (l.size() == nums.length) {
			List.add(new ArrayList<Integer>(l));
			return;
		}
		for (int i = 0; i < nums.length; i++) {
			if (used[i] || i > 0 && nums[i-1]==nums[i] && used[i - 1] == false)
				continue;
			used[i] = true;
			l.add(nums[i]);
			dfs(List, l, nums, used);
			used[i] = false;
			l.remove(l.size() - 1);
		}
	}
}





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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值