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
相关推荐
小月球~5 小时前
天梯赛 · 并查集
数据结构·算法
仍然.5 小时前
算法题目---模拟
java·javascript·算法
6Hzlia6 小时前
【Hot 100 刷题计划】 LeetCode 118. 杨辉三角 | C++ 动态规划题解
c++·leetcode·动态规划
潇冉沐晴7 小时前
DP——背包DP
算法·背包dp
GIOTTO情8 小时前
2026 世界互联网大会亚太峰会|AI 时代媒介投放的技术实战与算法优化
人工智能·算法
逆境不可逃8 小时前
LeetCode 热题 100 之 543. 二叉树的直径 102. 二叉树的层序遍历 108. 将有序数组转换为二叉搜索树 98. 验证二叉搜索树
算法·leetcode·职场和发展
计算机安禾8 小时前
【数据结构与算法】第19篇:树与二叉树的基础概念
c语言·开发语言·数据结构·c++·算法·visual studio code·visual studio
副露のmagic8 小时前
哈希章节 leetcode 思路&实现
算法·leetcode·哈希算法
副露のmagic8 小时前
字符串章节 leetcode 思路&实现
windows·python·leetcode
csuzhucong8 小时前
puzzle(1037)黑白、黑白棋局
算法