-
Notifications
You must be signed in to change notification settings - Fork 90
/
Unique_Binary_Search_Trees.js
104 lines (79 loc) · 2.2 KB
/
Unique_Binary_Search_Trees.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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
/*
Unique Binary Search Trees
https://leetcode.com/problems/unique-binary-search-trees/description/
Given n, how many structurally unique BST's (binary search trees) that store values 1 ... n?
Example:
Input: 3
Output: 5
Explanation:
Given n = 3, there are a total of 5 unique BST's:
1 3 3 2 1
\ / / / \ \
3 2 1 1 3 2
/ / \ \
2 1 2 3
DP Solution: https://www.programcreek.com/2014/05/leetcode-unique-binary-search-trees-java/
*/
// Solution 3 using DP
var numTrees3 = function (n) {
if (n == 0) return 0;
var map = [];
map[0] = 1;
map[1] = 1;
for (var i = 2; i <= n; i++) {
var currentI = 0;
for (var j = 0; j < i; j++) {
currentI += map[j] * map[i - j - 1];
}
map[i] = currentI;
}
return map[n];
};
// Solution 2 (Solution 1 + Memoization)
var numTrees2 = function (n) {
var memo = {};
return numTreesAux2(1, n, memo);
};
var numTreesAux2 = function (leftMin, leftMax, memo) {
const keyMemo = buildKey(leftMin, leftMax);
if (memo[keyMemo]) return memo[keyMemo];
if (leftMin > leftMax) return 0;
if (leftMin === leftMax) return 1;
var count = 0;
for (var i = leftMin; i <= leftMax; i++) {
const left = numTreesAux2(leftMin, i - 1, memo);
const right = numTreesAux2(i + 1, leftMax, memo);
if (left > 0 && right > 0) {
count += left * right;
} else {
count += left > 0 ? left : right;
}
}
memo[keyMemo] = count;
return count;
};
var buildKey = function (a, b) {
return a + "-" + b;
};
// Solution 1
var numTrees1 = function (n) {
return numTreesAux1(1, n);
};
var numTreesAux1 = function (leftMin, leftMax) {
if (leftMin > leftMax) return 0;
if (leftMin === leftMax) return 1;
var count = 0;
for (var i = leftMin; i <= leftMax; i++) {
const left = numTreesAux1(leftMin, i - 1);
const right = numTreesAux1(i + 1, leftMax);
if (left > 0 && right > 0) {
count += left * right;
} else {
count += left > 0 ? left : right;
}
}
return count;
};
module.exports.numTrees1 = numTrees1;
module.exports.numTrees2 = numTrees2;
module.exports.numTrees3 = numTrees3;