Question: http://oj.leetcode.com/problems/generate-parentheses/

Question Name: Generate Parentheses

A good question to show the good side of recursion. Memorization could improve the performance.

1 2 3 4 5 6 7 8 9 10 11 12 | class Solution: # @param two integer: the number of remaining "(" and ")" # @return a list of string def _generateParenthesis(self, n, m): if n == 0: return [")"*m] elif n == m: return ["("+i for i in self._generateParenthesis(n-1, m)] else: return ["("+i for i in self._generateParenthesis(n-1, m)] + [")"+i for i in self._generateParenthesis(n, m-1)] # @param an integer # @return a list of string def generateParenthesis(self, n): return self._generateParenthesis(n, n) |