Leetcode_22 generation [brackets]

Article Directory:

  • topic
  • A script
  • A script logic
  • shell script Share

topic:

N represents the number of generation is given in parentheses, you write a function, it is possible to generate all possible combinations of brackets and effective.

For example, given n = 3, to generate the result is:

[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]


A script: [when using: 36ms]

class Solution:
    def generateParenthesis(self, n: int) -> List[str]:
        lists = []
        if n >0 and not lists :lists.append("(")
        while lists:
            zuo = lists[0].count("(")
            you = lists[0].count(")")
            if zuo > you:
                if zuo == n:
                    lists.append(lists[0]+")")
                    lists.pop(0)
                else:
                    lists.append(lists[0] + ")")
                    lists.append(lists[0] + "(")
                    lists.pop(0)
            else:
                if zuo == n:
                    return(lists)
                else:
                    lists.append(lists[0] + "(")
                    lists.pop(0)

A script logic:

  • Generation roadmap brackets are:
    • First: from whatever position counting from left to right, a left parenthesis is the number must be greater than or equal to the right parenthesis, such as (() and (())
    • Second: the number of the left parenthesis is smaller than the target number n, can be coupled with a left bracket (and this element is added in the right parenthesis ")" on the basis of this element consisting of two new elements, and then the old delete element
    • Third: When the number of left parenthesis equal to the target number n, you can only add a closing parenthesis ")", and then delete the old elements on the basis of this element
    • Fourth: In the third basis, if the number equal to the number of left parenthesis right parenthesis, you can stop the cycle, and returns the results

shell solving Share:

https://blog.csdn.net/weixin_43428906/article/details/102790053

This link is the author of an earlier time using the shell can resolve this question, interested friends to share

Guess you like

Origin www.cnblogs.com/mailong/p/12037807.html