Given n, how many structurally unique BST’s (binary search trees) that store values 1 … n?
Example:
1 | Input: 3 |
we set dp[n] is the number of BST that store n consecutive values
we can get dp[n] as follows:
we set 1 as root node, so left subtree has 0 children, right subtree has n - 1 children, the number of bst is dp[0] * dpn - 1;
we set 2 as root node, so left subtree has 1 children, right subtree has n - 2 children, the number of bst is dp[1] * dp[n - 2];
generally, we set k as root noode, so left subtree has k - 1 children, right subtree has n - k children, the number of bst is dp[k - 1] * dp[n - k];
dp[n] = d[0] dp[n - 1] + … + dp[k - 1] dp[n - k] + … + dp[n - 1] * dp[0];
1 | class Solution { |