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
Use dp[i] to memory i nodes BST.
dp[0] = 1; dp[1] = 1
Things get complicate from 2 nodes:
2 nodes : 0, 1.
If we take 0 as the root. Then, there is 1 node left, one 1 BST.
If we take 0 as the root, then, there is 1 node left, one 1 BST ---- thus, there are 2 BSTs in total.
3 nodes: 0, 1, 2
If we take 0 as the root, there are 2 nodes left, thus the BSTs == dp[2];
If we take 1 as the root, there are 2 nodes left, one on the left, one on the right, thus, all the possibilities: dp[1] * dp[1] (Notice, here is not Plus)
If we take 2 as the root, there are 2 nodes left, two both are on the left, thus BSTs = dp[2].. --- Thus the sum is dp[2] + dp[1] * dp[1] + dp[2]
4 nodes: 0, 1, 2, 3
If we take 0 as the root, there are 3 nodes left, thus the BSTs = dp[0]*dp[3]
If we take 1 as the root, there are 3 nodes left, one on the left, two on the right, thus, BSTs = dp[1] * dp[2];
If we take 2 as the root, there are 3 nodes left, two on the left, one on the right, thus BSTs = dp[2] * dp[1];
If we take 3 as the root, there are 3 nodes left, three on the left, thus, BSTs = dp[3]*dp[0] ----> dp[0]*dp[3] + dp[1][2] + dp[2]*dp[1] + dp[3]*dp[0]
.....so on and so forth.....
int numTrees(int n) { vector<int> dp(n + 1, 0); dp[0] = dp[1] = 1; for(int i = 2; i <= n; ++i) { for(int j = 0; j < i; ++j) { dp[i] += dp[j]*dp[i-1-j]; } } return dp[n]; }