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
My code:
class Solution:
def numTrees(self, n):
"""
:type n: int
:rtype: int
"""
if n==0:
return 0
self.matrix=[[-1 for m in range(n)] for m in range(n)]
count=self.Set_node(1,n)
return int(count)
def Set_node(self,start,end):
if start>end:
return 1
if self.matrix[start-1][end-1]!=-1:
return self.matrix[start-1][end-1]
all_trees=0
for i in range(start,end+1):
left_trees=self.Set_node(start,i-1)
right_trees=self.Set_node(i+1,end)
all_trees+=left_trees*right_trees
self.matrix[start-1][end-1]=all_trees
return all_trees
Solution: https://leetcode.com/problems/unique-binary-search-trees/