2021-12-20

WARNING: This article may be obsolete
This post was published in 2021-12-20. Obviously, expired content is less useful to users if it has already pasted its expiration date.
This article is categorized as "Garbage" . It should NEVER be appeared in your search engine's results.


Leetcode 22

🔗 [Generate Parentheses - LeetCode] https://leetcode.com/problems/generate-parentheses/submissions/

在一张表上走方格,对走方格的方式进行了一定的限制,使用DFS遍历所有走法:

不同PDF阅读器的显示效果不同,如果渲染PDF出现偏差,请尝试其他PDF阅读器
from typing import List


class Solution:
    def generateParenthesis(self, n: int) -> List[str]:
        summary = []
        self.dp_table_dfs(x=0, y=0, lst='', n=n, summary=summary)
        return summary

    def dp_table_dfs(self, x, y, lst, n, summary):
        if x > n or y > n:
            return
        if x == n and y == n:
            summary.append(lst)
            return
        else:
            if x == y:
                self.dp_table_dfs(x, y + 1, lst + '(', n, summary)
            else:
                self.dp_table_dfs(x + 1, y, lst + ')', n, summary)
                self.dp_table_dfs(x, y + 1, lst + '(', n, summary)
        return


if __name__ == '__main__':
    print(Solution().generateParenthesis(n=3))


 Last Modified in 2022-01-22 

Leave a Comment Anonymous comment is allowed / 允许匿名评论