[Leetcode] [Python]22:generate parentheses

Source: Internet
Author: User

#-*-Coding:utf8-*-
‘‘‘
__author__ = ' [email protected] '

22:generate parentheses
https://oj.leetcode.com/problems/generate-parentheses/

Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
For example, given n = 3, a solution set is:
"((()))", "(()())", "(())()", "()(())", "()()()"

===comments by dabay===
Recursion.
Use left and right to record the remaining number of brackets.
If none is left, put the result in the list that you want to return.
If the left parenthesis is more than the closing parenthesis, the description is not a valid combination and is returned.
‘‘‘

Class Solution:
# @param an integer
# @return A list of string
def generateparenthesis (self, N):
Def GenerateParenthesis2 (left, right, string, res):
If left = = 0 and right = = 0:
Res.append (String)
Return
If left > right:
Return
If left > 0:
GenerateParenthesis2 (Left-1, right, String + "(", RES)
If right > 0:
GenerateParenthesis2 (left, right-1, String + ")", RES)

res = []
GENERATEPARENTHESIS2 (n, N, "", RES)
return res


def main ():
Sol = solution ()
Print Sol.generateparenthesis (4)


if __name__ = = ' __main__ ':
Import time
Start = Time.clock ()
Main ()
Print "%s sec"% (Time.clock ()-start)

[Leetcode] [Python]22:generate parentheses

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.