LeetCode 96. Unique Binary Search Trees (Medium)

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

 

Constraints:

  • 1 <= n <= 19
 方法:DP
思路:这题感觉是很妙的题。一开始完全没有想到竟然会是用DP来做。
1 定义dp[i] to be the number of unqiue BST trees when n = i 
2 dp[i] = dp[i-j-1] * dp[j]. For exmaple, when n = 7 and we choose i = 3 to be the root of the tree. Then the number of unique BST equals product of the number of trees when n = 2 and n = 4. (dp[2] * dp[4])
3 initialize dp[0] = 1 and dp[1]. Because we could only construct one BST tree when n = 0 or 1. 
4 the final answer would be dp[n]
time complexity: O(N^2) space complexity: O(N)
class Solution:
    def numTrees(self, n: int) -> int:
        dp = [0 for i in range(n+1)]
        
        dp[0] = 1 #n = 0, there is one structurally unique BST 
        dp[1] = 1 # n = 1 => one structurally unique BST 
        
        for i in range(2, n+1):
            for j in range(i):
                dp[i] += dp[i-j-1] * dp[j] 
                
        return dp[n]

 

posted @ 2020-11-17 10:51  Sheanne  阅读(96)  评论(0)    收藏  举报