题目描述:
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:
[ "((()))", "(()())", "(())()", "()(())", "()()()" ]
思路:感觉应该是要用递归解决,但是不大会写递归的代码....还得练一练。
Discuss:
def generate(p, left, right, parens=[]):
if left: generate(p + '(', left-1, right)
if right > left: generate(p + ')', left, right-1)
if not right: parens += p,
return parens
return generate('', n, n)
学到:
- 递归的写算法题还是很有用的,虽然时间复杂度会很高,有些题确实比较需要,代码看起来会比较简洁。