EX96
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:
将不同的n拥有的不重复的二叉树总数用G(n)来表示
F(i, n) =====> 以i为根的总数为n的二叉树总数
====> G(n) = F(1, n) + F(2, n) +……+ F(n, n)
====> F(i, n) = G(i-1) * G(n-i)
==========> G(n) = G(0) * G(n-1) + G(1) * G(n-2) + … + G(n-1) * G(0)
class Solution {
public:
int numTrees(int n) {
vector<int> dp(n+1, 0);
dp[0] = 1;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++) {
dp[i] += dp[j-1] * dp[i-j];
}
}
return dp[n];
}
};