27 lines
362 B
Go
27 lines
362 B
Go
|
package main
|
||
|
|
||
|
// Time: O(n^2)
|
||
|
// Space: O(n)
|
||
|
func numTrees(n int) int {
|
||
|
if n < 3 {
|
||
|
return n
|
||
|
}
|
||
|
trees := map[int]int{
|
||
|
0: 1,
|
||
|
1: 1,
|
||
|
2: 2,
|
||
|
}
|
||
|
for c := 3; c <= n; c++ {
|
||
|
s := 0
|
||
|
for p := 0; p < c/2; p++ {
|
||
|
s += trees[p] * trees[c-p-1] * 2
|
||
|
}
|
||
|
if (c-1)%2 == 0 {
|
||
|
p := (c - 1) / 2
|
||
|
s += trees[p] * trees[p]
|
||
|
}
|
||
|
trees[c] = s
|
||
|
}
|
||
|
return trees[n]
|
||
|
}
|