Leetcode47 全排列 II

博客围绕LeetCode题目,要对可包含重复数字的序列按任意顺序返回所有不重复的全排列。采用Java中用数组实现的双端队列Deque<Integer> = new ArrayDeque<>()来解决该问题。

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

给定一个可包含重复数字的序列 nums ,按任意顺序 返回所有不重复的全排列。

输入:nums = [1,1,2]
输出:
[[1,1,2],
 [1,2,1],
 [2,1,1]]

 

力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台

  

class Solution {
    public List<List<Integer>> permuteUnique(int[] nums) {
        List<List<Integer>> res = new ArrayList<>();
        int[] used = new int[nums.length];
        Arrays.sort(nums);
        order(res,nums,new ArrayList<Integer>(),used);
        return res;

    }
    public void order(List<List<Integer>> res, int[] nums, ArrayList<Integer> tmp, int[] used) {
        if(tmp.size() == nums.length){
            res.add(new ArrayList(tmp));
            return;
        }
        for(int i = 0;i < nums.length;i++){
            //nums[i] == nums[i-1] && used[i-1]==0 实现去重,重复元素中从非第一个访问时需要跳过,因为访问肯定会重复了

            if(used[i] == 1 || (i > 0 && nums[i] == nums[i-1] && used[i-1] == 0)){
                continue;
            }
            used[i] = 1;
            tmp.add(nums[i]);
            order(res,nums,tmp,used);
            used[i] = 0;
            tmp.remove(tmp.size() - 1);

        }
    }
}

使用Deque<Integer> = new ArrayDeque<>(); 用数组实现的双端队列来实现

class Solution {
    public List<List<Integer>> permuteUnique(int[] nums) {
        List<List<Integer>> res = new ArrayList<>();
        if(nums.length == 0){
            return res;
        }
        boolean[] used = new boolean[nums.length];
        Arrays.sort(nums);
        Deque<Integer> path = new ArrayDeque<>();
        order(res,nums,path,used);
        return res;
    }
    private void order(List<List<Integer>> res,int[] nums,Deque<Integer> path,boolean[] used){
        if(path.size() == nums.length){
            res.add(new ArrayList(path));
            return;

        }
        for(int i = 0; i < nums.length;i++){
            if(used[i] || (i > 0 && nums[i] == nums[i-1] && !used[i-1])){
                continue;
            }
            path.addLast(nums[i]);
            used[i] = true;
            order(res,nums,path,used);
            path.removeLast();
            used[i] = false;
        }
    }
}

Java集合(四三): ArrayDeque_arraydeque方法_CodingALife的博客-CSDN博客

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值