File tree Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Original file line number Diff line number Diff line change
1
+ // "pure" dp
2
+ class Solution {
3
+ fun numTrees (n : Int ): Int {
4
+ val cache = IntArray (n + 1 ) { 1 }
5
+
6
+ for (node in 2 .. n) {
7
+ var res = 0
8
+ for (root in 1 .. node) {
9
+ val left = root - 1
10
+ val right = node - root
11
+ res + = cache[left] * cache[right]
12
+ }
13
+ cache[node] = res
14
+ }
15
+
16
+ return cache[n]
17
+ }
18
+ }
19
+
20
+ // recursion + memoization
21
+ class Solution {
22
+ fun numTrees (n : Int ): Int {
23
+ val cache = IntArray (n + 1 ) { - 1 }
24
+
25
+ fun count (root : Int ): Int {
26
+ if (root == 0 ) return 1
27
+ if (cache[root] != - 1 ) return cache[root]
28
+
29
+ var res = 0
30
+ for (left in 0 until root) {
31
+ val right = root - left - 1
32
+ res + = count(left) * count(right)
33
+ }
34
+
35
+ cache[root] = res
36
+ return res
37
+ }
38
+
39
+ return count(n)
40
+ }
41
+ }
You can’t perform that action at this time.
0 commit comments