LeetCode讲解篇之47. 全排列 II

文章目录

题目描述

题解思路

初始化一个nums中元素是否被访问的数组used、记录还需要递归的深度deep

遍历nums

如果当前元素被访问过或者当前元素等于前一个元素且前一个元素没被访问过就跳过该次遍历

否则选择当前元素,继续递归

直到deep为0,将此次递归选择的数组加入到结果集,退出递归

直到搜索完成,返回结果集

题解代码

python 复制代码
class Solution:
    def permuteUnique(self, nums: List[int]) -> List[List[int]]:
        nums.sort()
        n = len(nums)
        deep = n
        res = []
        tmp = []
        used = [False for _ in range(n)]
        def dfs():
            nonlocal deep
            if deep == 0:
                res.append([num for num in tmp])
                return
            for i in range(n):
                num = nums[i]
                if used[i] or (i > 0 and num == nums[i-1] and used[i-1] == False):
                    continue
                used[i] = True
                tmp.append(num)
                deep -= 1
                dfs()
                deep += 1
                tmp.pop()
                used[i] = False

        dfs()
        return res
相关推荐
IronMurphy4 小时前
【算法四十三】279. 完全平方数
算法
墨染天姬5 小时前
【AI】Hermes的GEPA算法
人工智能·算法
papership5 小时前
【入门级-数据结构-3、特殊树:完全二叉树的数组表示法】
数据结构·算法·链表
smj2302_796826525 小时前
解决leetcode第3911题.移除子数组元素后第k小偶数
数据结构·python·算法·leetcode
Beginner x_u6 小时前
链表专题:JS 实现原理与高频算法题总结
javascript·算法·链表
_深海凉_9 小时前
LeetCode热题100-寻找两个正序数组的中位数
算法·leetcode·职场和发展
踩坑记录10 小时前
leetcode hot100 寻找两个正序数组的中位数 hard 二分查找 双指针
leetcode
旖-旎10 小时前
深搜练习(电话号码字母组合)(3)
c++·算法·力扣·深度优先遍历
谭欣辰10 小时前
C++快速幂完整实战讲解
算法·决策树·机器学习
Mr_pyx10 小时前
【LeetHOT100】随机链表的复制——Java多解法详解
算法·深度优先