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.
1 3 3 2 1 / / / 3 2 1 1 3 2 / / 2 1 2 3
Solution:
count the number of ways. use DP.
(1) Define the subproblem
dp[i] indicate the number of unique BST rooted at i
(2) Find the recursion (state transition function)
a. there is 0 node, empty tree
dp[0] = 1
b. there is 1 node, just root node
dp[1] = 1
c. there is 2 nodes. number 1 is rooted, dp[0]*dp[1]; 2 is rooted dp[1]*dp[0]
dp[2] = dp[0]*dp[1] + dp[1]*dp[0]
d. there is 3 nodes. number 1 is rooted, dp[0]*dp[2]; 2 is rooted dp[1]*dp[1], 3 is rooted dp[2]*dp[0]
dp[3] = dp[0]*dp[2] + dp[1]*dp[1] + dp[2]*dp[0]
Therefore, the transition function is as follows;
dp[k] = summation(dp[i] * dp[k-1-i]) for i = 0 to k-1
and k from 2 to n
(3) Get the base case
dp[0] = 1
dp[1] = 1
1 dp = [0] * (n+1) 2 dp[0] = 1 3 dp[1] = 1 4 for k in range(2, n+1): 5 for i in range(0, k): 6 dp[k] += dp[i] * dp[k-1-i] 7 # print ("dp k: ", dp[k]) 8 9 return dp[n]