• leetcode22 Generate Parentheses


     1 """
     2  Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
     3 For example, given n = 3, a solution set is:
     4 [
     5   "((()))",
     6   "(()())",
     7   "(())()",
     8   "()(())",
     9   "()()()"
    10 ]
    11 """
    12 """
    13 每次增加括号时需要判断之前字符串中左右括号的个数
    14 判断增加‘(’或‘)’依据为,
    15 #若当前字符串的长度等于2n则字符串存入列表中
    16 若之前字符串中左括号个数小于n,则应增加左括号,
    17 若之前字符串中右括号个数小于左括号,则应增加右括号
    18 """
    19 class Solution:
    20     def generateParenthesis(self, n):
    21         result = []
    22         # 函数嵌套
    23         def trackback(S="", left=0, right=0):
    24             if len(S) == 2 * n:
    25                 result.append(S)
    26             if left < n:
    27                 trackback(S + '(', left + 1, right)
    28             if right < left:
    29                 trackback(S + ')', left, right + 1)
    30         trackback()
    31         return result
  • 相关阅读:
    升级Visual Studio安装已完成,出现警告
    C# 字符串格式
    C# TimeSpan
    git 手册
    Mac clion 远程调试 linux 服务器进程
    C++ 左值引用和右值引用的用处
    Mac OS 快捷键
    MacPorts Guide
    同步异步阻塞非阻塞
    tcp 简单实现
  • 原文地址:https://www.cnblogs.com/yawenw/p/12310874.html
Copyright © 2020-2023  润新知