We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent b9f60c2 commit f6b987bCopy full SHA for f6b987b
javascript/0096-unique-binary-search-trees.js
@@ -0,0 +1,26 @@
1
+/**
2
+ * Time O(n^2) | Space O(n) | n^2 because of the inner loop which runs from 0 to n on each call.
3
+ * DFS | DP | Recursion | Tree
4
+ * https://leetcode.com/problems/unique-binary-search-trees/
5
+ * @param {number} n
6
+ * @return {number}
7
+ */
8
+var numTrees = function(n) {
9
+
10
+ const cache = {};
11
12
+ const dfs = (n) => {
13
+ if(n <= 1) return 1;
14
+ if(cache[n]) return cache[n];
15
16
+ let total = 0;
17
+ for(let i = 0; i < n; i++) {
18
+ total += dfs(i) * dfs(n-1-i);
19
+ }
20
21
+ cache[n] = total;
22
+ return total;
23
24
25
+ return dfs(n);
26
+};
0 commit comments