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;
            }
        }
    }
}
相关推荐
Navigator_Z6 小时前
LeetCode //C - 1317. Convert Integer to the Sum of Two No-Zero Integers
c语言·算法·leetcode
D e re k ZH7 小时前
C++ 标准库算法全景指南
数据结构·c++·算法
冻柠檬飞冰走茶7 小时前
字母移动游戏题解:贪心求最长可保留连续子串(附 C 实现)
c语言·开发语言·数据结构·算法·动态规划
雪落漂泊8 小时前
C++算法 二分查找篇(上)
开发语言·c++·算法
LabVIEW开发10 小时前
LabVIEW 连接板:28 个端子怎么排,优先级怎么定
java·算法·labview
严肃小白兔11 小时前
MATLAB 数值计算中的精度与误差问题:浮点运算、误差传播与数值稳定性
人工智能·算法·matlab
青少儿编程课堂12 小时前
蓝桥杯青少组图形化省考报名倒计时·全国青少年信息素养大赛·电子学会图形化考级:校园黑白棋人机对战解析
c++·python·算法·bfs·信息学竞赛
jktantan13 小时前
注解式脱敏:用 Jackson 的 ContextualSerializer 做字段级策略(一)
spring boot·后端·算法·spring cloud·系统架构
Dream it possible!1 天前
LeetCode 面试经典 150_多维动态规划_交错字符串(97_C++_中等)
算法·leetcode·面试·动态规划