Problem
Given n, how many structurally unique BST’s (binary search trees) that store values 1 … n?
Example:
1 | |
Explanation
-
We can use dynamic programming to solve this problem.
-
Dynamic state is a one dimensional array,
dp[n]means when input isn, the total number of unique BST. -
Dynamic init is
dp[0] = 1,dp[1] = 1. For example, whennis 1, we only have one way to struct the unique BST. -
Dynamic function. When
n = 2, the total number of unqiue BST is 2, in other word, the root node can be 1, right node can be 2; or root node is 2, left node is 1. Whenn = 3, we have three cases: when root node is element 1, there is 0 node on the left and there are 2 nodes on the right; when root node element is 2, there is 1 node on the left and 1 node on the right; when root node is element 3, there are 2 nodes on the left and 0 node on the right. We can illustrate it below:1
2
31 2 3 / \ / \ / \ 0 2 1 1 2 0 -
From the above illustration, input
n=3, when root node is element 1, it can only have 0 node on the left and 2 nodes on the right, and there are 2 unique ways becausedp[0] = 1,dp[2] = 2, and1 * 2 = 2. When root node is element 2, there is one node on the left and one on the right, and there is 1 unique way becausedp[1] = 1,1 * 1 = 1. When root node is element 3, there are two node on the left and zero node on the right, and there are 2 unique ways becausedp[2] = 2,dp[0] = 1,2 * 1 = 2. Therefore, when input is3, we havedp[0]*dp[2] + dp[1]*dp[1] + dp[2]*dp[0] = 5unique ways. So, when input isn, if there is0node on the left, then there aren-1node on the right because we need to subtract there is 1 root node.
Solution
1 | |