File tree Expand file tree Collapse file tree 1 file changed +9
-20
lines changed
Expand file tree Collapse file tree 1 file changed +9
-20
lines changed Original file line number Diff line number Diff line change 1- # -*- coding: utf-8 -*-
2-
31class Solution :
4- def __init__ (self ):
5- self .cache = {}
6-
72 # @paramn n: An integer
83 # @return: An integer
94 def numTrees (self , n ):
10- if n <= 1 :
5+ # write your code here
6+ # 只需要计算数量,不需要计算每棵树的形状,所以缓存结果就可以了。
7+ if n == 0 :
118 return 1
12- else :
13- if n in self .cache :
14- return self .cache [n ]
15- else :
16- sum = 0
17- for i in xrange (1 , n + 1 ):
18- left_num , right_num = 1 , 1
19- if i > 0 :
20- left_num = self .numTrees (i - 1 ) # 计算左子树数量
21- if i < n :
22- right_num = self .numTrees (n - i ) # 计算右子树数量
23- sum += left_num * right_num
24- self .cache [n ] = sum
25- return self .cache [n ]
9+ methods = [0 ] * (n + 1 )
10+ methods [0 ], methods [1 ] = 1 , 1
11+ for i in xrange (2 , n + 1 ):
12+ for j in xrange (1 , i + 1 ):
13+ methods [i ] += methods [j - 1 ] * methods [i - j ]
14+ return methods [- 1 ]
You can’t perform that action at this time.
0 commit comments