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;
            }
        }
    }
}
相关推荐
Python×CATIA工业智造5 分钟前
详细页智能解析算法:洞悉海量页面数据的核心技术
爬虫·算法·pycharm
无聊的小坏坏1 小时前
力扣 239 题:滑动窗口最大值的两种高效解法
c++·算法·leetcode
黎明smaly1 小时前
【排序】插入排序
c语言·开发语言·数据结构·c++·算法·排序算法
YuTaoShao1 小时前
【LeetCode 热题 100】206. 反转链表——(解法一)值翻转
算法·leetcode·链表
YuTaoShao1 小时前
【LeetCode 热题 100】142. 环形链表 II——快慢指针
java·算法·leetcode·链表
CCF_NOI.2 小时前
(普及−)B3629 吃冰棍——二分/模拟
数据结构·c++·算法
运器1232 小时前
【一起来学AI大模型】支持向量机(SVM):核心算法深度解析
大数据·人工智能·算法·机器学习·支持向量机·ai·ai编程
Zedthm2 小时前
LeetCode1004. 最大连续1的个数 III
java·算法·leetcode
神的孩子都在歌唱3 小时前
3423. 循环数组中相邻元素的最大差值 — day97
java·数据结构·算法
YuTaoShao3 小时前
【LeetCode 热题 100】73. 矩阵置零——(解法一)空间复杂度 O(M + N)
算法·leetcode·矩阵