【leetcode】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:

"((()))", "(()())", "(())()", "()(())", "()()()"

解题思路:

递归,用两个数组分别表示两种括号

class Solution:
    def f(self,res,s,n,m):
        if n == 0 and m == 0:
            res.append(s)
            return 
        if m > 0:
            self.f(res,s+')',n,m-1)
        if n > 0:
            self.f(res,s+'(',n-1,m+1)

    # @param an integer
    # @return a list of string
    def generateParenthesis(self, n):
        s = ''
        res = []
        self.f(res,s,n,0)
        return res

你可能感兴趣的:(LeetCode)