ZhangZhihui's Blog  

Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

 

Example 1:

Input: n = 3
Output: ["((()))","(()())","(())()","()(())","()()()"]

Example 2:

Input: n = 1
Output: ["()"]

 

Constraints:

  • 1 <= n <= 8

 

ChatGPT's Solution:

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

        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)
        
        backtrack('', 0, 0)
        return result

 

 

This implementation:

  • Uses backtracking to explore all valid sequences.

  • Ensures that an open parenthesis ( is added only if open_count < n.

  • Ensures that a closing parenthesis ) is added only if close_count < open_count.

 

posted on 2025-04-01 21:20  ZhangZhihuiAAA  阅读(11)  评论(0)    收藏  举报