[LeetCode]Permutations II

本文介绍了一个中等难度的问题,即给定可能包含重复数字的集合,返回所有可能的唯一排列。通过递归方法并利用哈希集跳过重复元素来解决此问题。代码示例使用了Java语言。

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


本题难度Medium。

【复杂度】
时间 O(N!) 空间 O(N)

【思路】
与Permutations不一样的地方就是有duplicates。办法就是跳过duplicates(29-33行)。其他不变。

【代码】

public class Solution {
    public List<List<Integer>> permuteUnique(int[] nums) {
        //require
        List<List<Integer>> ans=new ArrayList<>();
        if(nums==null)
            return ans;
        int size=nums.length;
        if(size<1)
            return ans;
        List<Integer> list=new ArrayList<Integer>(),remains=new ArrayList<Integer>();
        for(int n:nums)
            remains.add(n);
        //invariant
        helper(list,remains,ans);
        //ensure
        return ans;
    }

    private void helper(List<Integer> preList,List<Integer> remains,List<List<Integer>> ans){
        //bound
        if(remains.size()==0){
            List<Integer> list=new ArrayList<Integer>(preList);
            ans.add(list);
            return;
        }
        Set<Integer> set=new HashSet<Integer>();
        for(int i=0;i<remains.size();i++){
            int n=remains.get(0);
            if(set.contains(n)){
                remains.remove(0);
                remains.add(n);
                continue;
            }
            set.add(n);
            remains.remove(0);
            preList.add(n);
            helper(preList,remains,ans);
            remains.add(n);
            preList.remove(preList.size()-1);
        }
    }
}

参考

[LeetCode]Permutations

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值