forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0096-unique-binary-search-trees.kt
More file actions
41 lines (34 loc) · 925 Bytes
/
0096-unique-binary-search-trees.kt
File metadata and controls
41 lines (34 loc) · 925 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
//"pure" dp
class Solution {
fun numTrees(n: Int): Int {
val cache = IntArray (n + 1) { 1 }
for (node in 2..n) {
var res = 0
for (root in 1..node) {
val left = root - 1
val right = node - root
res += cache[left] * cache[right]
}
cache[node] = res
}
return cache[n]
}
}
//recursion + memoization
class Solution {
fun numTrees(n: Int): Int {
val cache = IntArray (n + 1) { -1 }
fun count(root: Int): Int {
if (root == 0) return 1
if (cache[root] != -1) return cache[root]
var res = 0
for (left in 0 until root) {
val right = root - left - 1
res += count(left) * count(right)
}
cache[root] = res
return res
}
return count(n)
}
}