|
| 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