Skip to content

Commit 4fd1e72

Browse files
authored
Create 0096-unique-binary-search-trees.kt
1 parent 99e5abf commit 4fd1e72

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
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+
}

0 commit comments

Comments
 (0)