-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path96.不同的二叉搜索树.js
54 lines (49 loc) · 1007 Bytes
/
96.不同的二叉搜索树.js
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
42
43
44
45
46
47
48
49
50
51
52
53
54
/*
* @lc app=leetcode.cn id=96 lang=javascript
*
* [96] 不同的二叉搜索树
*/
// @lc code=start
/**
* @param {number} n
* @return {number}
*/
let memo
var numTrees = function(n) {
memo = initMemo(n)
// count BST in [1,n]
return count(1, n)
}
function initMemo(n) {
const memo = []
for (let i = 0; i < n + 1; i++) {
if (!memo[i]) {
memo[i] = []
}
for (let j = 0; j < n + 1; j++) {
memo[i][j] = 0
}
}
return memo
}
// count BST in [lo, hi]
function count(lo, hi) {
// [lo,hi] is empty array, should count as one situation
if (lo > hi) return 1
if (memo[lo][hi] !== 0) {
return memo[lo][hi]
}
let res = 0
for (let mid = lo; mid <= hi; mid++) {
// i as root
let left = count(lo, mid - 1)
let right = count(mid + 1, hi)
// total = left subTree * right subTree
// eg: i = 3, left{1,2}, right{4,5} => left * right = 2 * 2 = 4
res += left * right
}
memo[lo][hi] = res
return res
}
numTrees(5)
// @lc code=end