Given n, how many structurally unique BST's (binary search trees) that store values 1...n?
For example,
Given n = 3, there are a total of 5 unique BST's.
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
Solution:
class Solution: # @return an integer def numTrees(self, n): return self.numTrees2(1, n) def numTrees2(self, minV, maxV): if minV >= maxV: return 1 val = 0 for i in range(minV,maxV+1): val = val + self.numTrees2(minV, i-1)*self.numTrees2(i+1, maxV) return val
No comments :
Post a Comment