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
大意:给定一个整数 n,求以 1 … n 为节点组成的二叉搜索树有多少种?
方法:
代码:
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;i++){
int sum=0;
for(int j=0;j<i;j++){
sum+=dp[j]*dp[i-j-1]; //dp[j]为左子树个数,dp[i-j-1]为右子树个数
}
dp[i]=sum;
}
return dp[n];
}
};