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 f9d63fc commit 93a29b3Copy full SHA for 93a29b3
14. Questions/leetcode 96 - unique binary search trees.py
@@ -0,0 +1,21 @@
1
+# unique binary search trees | leetcode 96 | https://leetcode.com/problems/unique-binary-search-trees/
2
+# method: dp, use cached results for subtrees of all possible roots
3
+
4
+class Solution:
5
+ def numTrees(self, n: int) -> int:
6
+ # cache of possible trees
7
+ possibleTrees = [1] * (n + 1)
8
9
+ # for each number of nodes
10
+ for numNodes in range(2, n + 1):
11
12
+ # for each possible root
13
+ possibleSubTrees = 0
14
+ for possibleRoot in range(1, numNodes + 1):
15
+ Left = possibleRoot - 1
16
+ Right = numNodes - possibleRoot
17
+ possibleSubTrees += possibleTrees[Left] * possibleTrees[Right]
18
+ possibleTrees[numNodes] = possibleSubTrees
19
20
+ return possibleTrees[n]
21
0 commit comments