LeetCode_Everyday:022 Generate Parentheses

LeetCode_Everyday:022 Generate Parentheses


LeetCode Everyday:堅持價值投資,做時間的朋友!!!

題目:

數字n代表生成括號的對數,請你設計一個函數,用於能夠生成所有可能的並且有效的括號組合。

示例:

  • 示例 1:
    輸入:n = 3
    輸出:[
           "((()))",
           "(()())",
           "(())()",
           "()(())",
           "()()()"
         ]
    

代碼

方法一: 深度優先遍歷 題解

執行用時:40 ms, 在所有 Python3 提交中擊敗了83.34%的用戶
內存消耗:13.9 MB, 在所有 Python3 提交中擊敗了6.06%的用戶

from typing import List


class Solution:
    def generateParenthesis(self, n: int) -> List[str]:
        res = []
        cur_str = ''

        def dfs(cur_str, left, right):
            """
            :param cur_str: 從根結點到葉子結點的路徑字符串
            :param left: 左括號還可以使用的個數
            :param right: 右括號還可以使用的個數
            :return:
            """
            if left == 0 and right == 0:
                res.append(cur_str)
                return
            if right < left:
                return
            if left > 0:
                dfs(cur_str + '(', left - 1, right)
            if right > 0:
                dfs(cur_str + ')', left, right - 1)

        dfs(cur_str, n, n)
        return res

"""
For Example:    input:    n = 3
               output:  [
                           "((()))",
                           "(()())",
                           "(())()",
                           "()(())",
                           "()()()"
                         ]
"""
n = 3
                
solution = Solution()
result = solution.generateParenthesis(n)
print('輸出爲:', result)

方法二: 遞循環遍歷 題解

執行用時:52 ms, 在所有 Python3 提交中擊敗了29.10%的用戶
內存消耗:13.9 MB, 在所有 Python3 提交中擊敗了6.06%的用戶

from typing import List


class Solution:
    def generateParenthesis(self, n: int) -> List[str]:
        if n == 0:
            return []

        dp = [None for _ in range(n + 1)]
        dp[0] = [""]

        for i in range(1, n + 1):
            cur = []
            for j in range(i):
                left = dp[j]
                right = dp[i - j - 1]
                for s1 in left:
                    for s2 in right:
                        cur.append("(" + s1 + ")" + s2)
            dp[i] = cur
        return dp[n]

"""
For Example:    input:    n = 3
               output:  [
                           "((()))",
                           "(()())",
                           "(())()",
                           "()(())",
                           "()()()"
                         ]
"""
n = 3
                
solution = Solution()
result = solution.generateParenthesis(n)
print('輸出爲:', result)
      

參考

  1. https://leetcode-cn.com/problems/generate-parentheses/solution/hui-su-suan-fa-by-liweiwei1419/

此外

  • 原創內容轉載請註明出處
  • 請到我的GitHub點點 star
  • 關注我的 CSDN博客
  • 關注我的嗶哩嗶哩
  • 關注公衆號:CV伴讀社

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章