Description
Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
Code
class Solution(object):
def generateParenthesis(self, n):
rst = []
def generate(lcnt, rcnt, str): # lcnt和rcnt是用过的左右括号数量,str是目前的生成序列
if lcnt + rcnt == 2 * n:
rst.append(str)
return;
if lcnt < n:
generate(lcnt+1, rcnt, str+'(')
if rcnt < lcnt:
generate(lcnt, rcnt + 1, str+')')
generate(0, 0, '')
return rst
Note
- 思路
需要想明白一件事,在生成序列的任意位置之前,只要右括号不多于左括号,那么就是正确的序列!
- python中变量作用域
一个函数中定义的变量是local的,函数之外不能直接访问;但如果把函数中的变量定义为global的,那么就可以在函数外直接访问。
- 函数中定义函数
关于这点我还没太搞明白, 因为没有用过闭包、decorator等,所以对这些概念不太了解。
以上的代码中,需要注意的是在generateParenthesis()函数中定义的generate()函数,不必在参数中写上self,调用时也不用通过self。据说python中万物皆对象,函数也是如此。因为generate()这个函数并没有被作为返回值返回,所以之后就无法从外部访问了。