Given n, how many structurally unique BST's (binary search trees) that store values 1 ... n?
Example:
Input: 3 Output: 5 Explanation: 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
根据http://www.cnblogs.com/grandyang/p/4299608.html的讲解,
当n=3的计算方法:
dp[3] = dp[0] * dp[2] (1为根的情况) (小于1的数为0,大于1的数有2个,大于1的那两个数的BST的个数为dp[2])
+ dp[1] * dp[1] (2为根的情况)
+ dp[2] * dp[0] (3为根的情况)
C++代码(BP算法):
class Solution {
public:
int numTrees(int n) {
vector<int>dp(n+1,0);
dp[0] = 1;
dp[1] = 1;
for(int i=2; i<n+1; i++){
for(int j=0; j<i; j++){
dp[i]+=dp[j]*dp[i-j-1];
}
}
return dp[n];
}
};