Bracket generation-LeetCode

topic:

Insert picture description here
Original link: https://leetcode-cn.com/problems/generate-parentheses/

Ideas:

  1. The brute force method is to recursively generate all combinations, and at the same time determine whether they meet the requirements
  2. Backtracking method, there is no need to judge after generating a complete combination, because there are at most two placement methods at each position: when there is still a left parenthesis, place the left parenthesis; the number of left parentheses that have been placed in the current combination When greater than the number of right parentheses, place the right parenthesis
  3. Then take a step back, reverse the operation status value (here the status value is temporary storage space), and see which situation remains next

Code:

class Solution:
    def generateParenthesis(self, n: int) -> List[str]:
        result = []
        if n<=0: return result
        def back(temp, left, right):
            # 满足组合长度的条件,不需要判断是因为组合生成的方式保证了合理性
            if len(temp) == 2*n:
                result.append(''.join(temp))
                return
            # 还有左括号剩余
            if left<n:
                temp.append('(')
                back(temp, left+1, right)
                # 逆操作状态值
                temp.pop()
            # 已使用的左括号的个数大于右括号,说明此时放入右括号一定有左括号与其匹配
            if left>right:
                temp.append(')')
                back(temp, left, right+1)
                temp.pop()
        back([], 0, 0)
        return result

Guess you like

Origin blog.csdn.net/qq_35221523/article/details/112549797