递归(二)---力扣22括号生成,力扣78求子集

22. 括号生成https://leetcode.cn/problems/generate-parentheses/

括号生成

数字 n 代表生成括号的对数,请你设计一个函数,用于能够生成所有可能的并且 有效的括号组合。

示例 1:

复制代码
输入:n = 3
输出:["((()))","(()())","(())()","()(())","()()()"]

示例 2:

复制代码
输入:n = 1
输出:["()"]

提示:

  • 1 <= n <= 8

代码

复制代码
from typing import List

class Solution:
    def generateParenthesis(self, n: int) -> List[str]:
        def backtrack(current: str, open_count: int, close_count: int):
            if len(current) == 2 * n:
                result.append(current)
                return
            if open_count < n:
                backtrack(current + '(', open_count + 1, close_count)
            if close_count < open_count:
                backtrack(current + ')', open_count, close_count + 1)

        result = []
        backtrack('', 0, 0)
        return result
if __name__ == '__main__':
    s = Solution()
    print(s.generateParenthesis(3))

求子集

给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集

(幂集)。

解集 不能 包含重复的子集。你可以按 任意顺序 返回解集。

示例 1:

复制代码
输入:nums = [1,2,3]
输出:[[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]

示例 2:

复制代码
输入:nums = [0]
输出:[[],[0]]

提示:

  • 1 <= nums.length <= 10
  • -10 <= numsi <= 10
  • nums 中的所有元素 互不相同
复制代码
from typing import List

class Solution:
    def subsets(self, nums: List[int]) -> List[List[int]]:
        def backtrack(start: int, current: List[int]):
            # 每个状态都是一个有效的子集,所以都要加入结果集
            result.append(current[:])
            
            # 从start开始遍历,避免重复
            for i in range(start, len(nums)):
                # 选择当前数字
                current.append(nums[i])
                # 递归生成包含当前数字的子集
                backtrack(i + 1, current)
                # 回溯,移除当前数字
                current.pop()
        
        result = []
        backtrack(0, [])
        return result

if __name__ == '__main__':
    s = Solution()
    print(s.subsets([1,2,3]))

初始状态: \[\]

  • 添加 \[\] 到结果集

选择1:

  • 1

  • 添加 1 到结果集

选择1,2:

  • 1,2

  • 添加 1,2 到结果集

选择1,2,3:

  • 1,2,3

  • 添加 1,2,3 到结果集

回溯,移除3: 1,2

回溯,移除2: 1

选择1,3:

  • 1,3

  • 添加 1,3 到结果集

回溯,移除3: 1

回溯,移除1: \[\]

选择2:

  • 2

  • 添加 2 到结果集

选择2,3:

  • 2,3

  • 添加 2,3 到结果集

回溯,移除3: 2

回溯,移除2: \[\]

选择3:

  • 3

  • 添加 3 到结果集

相关推荐
星云穿梭1 天前
用Python写一个带图形界面的学生管理系统——完整教程
python
金銀銅鐵1 天前
用 Pygame 实现 15 puzzle
python·数学·游戏
黄忠1 天前
大模型之LangGraph技术体系
python·llm
hboot2 天前
AI工程师第二课 - 数据处理
人工智能·python·数据分析
用户8356290780512 天前
使用 Python 自动化 PowerPoint 形状布局与格式设置
后端·python
用户8356290780512 天前
用 Python 自动化 PowerPoint 演讲者备注添加
后端·python
黄忠2 天前
01-系统架构设计-LangGraph状态机与多源异构RAG
python
zzzzzz3102 天前
假如我是掘金管理员,我先给评论区装个'代码审查'系统
python·程序员·机器人
砍材农夫2 天前
python环境|conda安装和使用(2)
后端·python
程序员龙叔3 天前
编写高质量 Skill 系列 -- 如何设计需求分析与用例生成的 SKILL
自动化测试·软件测试·python·软件测试工程师·接口测试·性能测试·skill·ai测试