LeetCode_OJ【47】Permutations II

本文探讨如何在存在重复元素的数集上生成所有唯一排列。通过预先排序集合并递归过程中的智能决策,避免重复扩展路径,提高效率。Java实现展示了这一策略的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

Subscribe to see which companies asked this question


这道题目和上题思路差不多,不过要考虑去重。

如果对于每一个候选的解都查看当前结果集中是否包含该解,效率就太低了。

一个比较好的方法就是一开始对于给定的集合先排好序,然后递归过程中,每次扩展新节点,检查该节点和上次扩展的节点是否相同,相同则不扩展。

下面是JAVA实现:

public class Solution {
    public List<List<Integer>> permuteUnique(int[] nums) {
		List<List<Integer>> res = new ArrayList<List<Integer>>();
		List<Integer> middle = new ArrayList<Integer>();
		Arrays.sort(nums);
		for(int i = 0 ; i < nums.length ; i ++){
			middle.add(nums[i]);
		}
		List<Integer> path = new ArrayList<Integer>();
		getPermute(res, middle, path);
		return res;
    }
	
	public void getPermute(List<List<Integer>> res,List<Integer> nums,List<Integer> path){
		if(nums.size() == 0){
			res.add(new ArrayList<Integer>(path));
		}
		else{
			for(int i = 0 ; i < nums.size() ; i++){
				if(i > 0 && nums.get(i-1).intValue() == nums.get(i).intValue())
					continue;
				path.add(nums.get(i));
				nums.remove(i);
				getPermute(res, nums, path);
				nums.add(i,path.remove(path.size() -1));
			}
		}
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值