LeetCode47-全排列II-剪枝逻辑

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

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

其中visiti-1==False的话,就是代表了树层visiti-1使用过

其中visiti-1==True的话,就是代表了树枝visiti-1使用过

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

因为去重的逻辑是减去树层的重复项,因此当visiti-1==False的时候必须要跳过,也就是!visiti-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;
            }
        }
    }
}
相关推荐
垆边人似月.9 分钟前
华为题:污染水域
算法
All for pursuit.28 分钟前
【回溯-6】79.单词搜索
数据结构·c++·算法·leetcode
ZhangJun9531 分钟前
Mobike 共享单车分析项目
人工智能·python·算法·kmeans·聚类·knn
Navigator_Z38 分钟前
LeetCode //C - 1281. Subtract the Product and Sum of Digits of an Integer
c语言·算法·leetcode
薛定e的猫咪1 小时前
(AISTATS 2023)BaCaDI 逐章阅读
人工智能·深度学习·算法·机器学习
Benny_Tang1 小时前
AT_arc180_d [ARC180D] Division into 3 题解
数据结构·c++·算法
殷色玫瑰1 小时前
C++ STL:stack、queue、priority_queue 与容器适配器详解
java·开发语言·数据结构·c++·算法·visualstudio
Evand J2 小时前
【电机滤波例程1】PMSM永磁同步电机转速与位置估计,MATLAB程序:标准无迹卡尔曼滤波、模型说明与仿真验证
算法·matlab·电机·ekf·负载·卡尔曼滤波
打码的老程是远篁2 小时前
手把手教你玩转大模型——3. Transformer 的位置编码——模型怎么知道谁在前,谁在后?
人工智能·算法
嘎嘎风2 小时前
MiniMind 学习笔记之 06 一张图、一百行:MiniMind 的骨架
算法·源码