[Leetcode][Python]22: Generate Parentheses

1575 ワード

# -*- 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===

left right 。
, 。
, , 。
'''

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)