原題地址: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:
"((()))", "(()())", "(())()", "()(())", "()()()"
解題思路:列舉出所有合法的括號匹配,使用dfs。如果左括號的數量大於右括號的數量的話,就不能產生合法的括號匹配。
代碼:
class Solution: # @param an integer # @return a list of string # @draw a decision tree when n == 2, and you can understand it! def helpler(self, l, r, item, res): if r < l: return if l == 0 and r == 0: res.append(item) if l > 0: self.helpler(l - 1, r, item + '(', res) if r > 0: self.helpler(l, r - 1, item + ')', res) def generateParenthesis(self, n): if n == 0: return [] res = [] self.helpler(n, n, '', res) return res