LeetCode47-全排列II-剪枝逻辑

参考链接:
🔗:卡尔的代码随想录:全排列II

这里第一层,used只有一个元素为1,代表只取出了1个元素作为排列,第二层used有两个元素为1,代表取出了2个元素作为排列,因为数组有序,所以重复的元素都是挨着的,因此可以使用如下语句去重.

其中visit[i-1]==False的话,就是代表了树层visit[i-1]使用过

其中visit[i-1]==True的话,就是代表了树枝visit[i-1]使用过

java 复制代码
if(i>=1&&nums[i-1]==nums[i]&&!visit[i-1]){
    continue;
}

因为去重的逻辑是减去树层的重复项,因此当visit[i-1]==False的时候必须要跳过,也就是!visit[i-1]的时候要continue,不能是break,如果break了,下一个排列会被忽略掉了!

java 复制代码
class Solution {
    public List<List<Integer>> permuteUnique(int[] nums) {
        List<List<Integer>> paths=new ArrayList<>();
        Deque<Integer> path=new ArrayDeque<>();
        Arrays.sort(nums);
        boolean[] visit = new boolean[nums.length+1];
        dfs(nums,paths,path,visit);
        return paths;
    }

    public void dfs(int[] nums,List<List<Integer>> paths,Deque<Integer> path,boolean[] visit){
        if(nums==null){
            return ;
        }
        if(path.size()==nums.length){
            paths.add(new ArrayList(path));
            return;
        }
        // int i=begin;
        int i=0;
        for(;i<nums.length;++i){
            if(i>=1&&nums[i-1]==nums[i]&&!visit[i-1]){
                continue;
            }
            if(!visit[i]){
                visit[i]=true;
                path.add(nums[i]);
                dfs(nums,paths,path,visit);
                if(!path.isEmpty())
                    path.removeLast();
                visit[i]=false;
            }
        }
    }
}
相关推荐
轻微的风格艾丝凡3 分钟前
嵌入式定时器计时技巧:用有符号数省略溢出判断的底层逻辑与实践
数据库·算法·dsp开发·嵌入式软件
No0d1es9 分钟前
2025年12月 GESP CCF编程能力等级认证C++四级真题
算法·青少年编程·等级考试·gesp·ccf
CodeByV27 分钟前
【算法题】快排
算法
一起努力啊~29 分钟前
算法刷题--长度最小的子数组
开发语言·数据结构·算法·leetcode
rchmin33 分钟前
限流算法:令牌桶与漏桶详解
算法·限流
leoufung41 分钟前
LeetCode 221:Maximal Square 动态规划详解
算法·leetcode·动态规划
黑符石43 分钟前
【论文研读】Madgwick 姿态滤波算法报告总结
人工智能·算法·机器学习·imu·惯性动捕·madgwick·姿态滤波
源代码•宸1 小时前
Leetcode—39. 组合总和【中等】
经验分享·算法·leetcode·golang·sort·slices
好易学·数据结构1 小时前
可视化图解算法77:零钱兑换(兑换零钱)
数据结构·算法·leetcode·动态规划·力扣·牛客网
AlenTech1 小时前
226. 翻转二叉树 - 力扣(LeetCode)
算法·leetcode·职场和发展