https://leetcode.com/problems/unique-binary-search-trees/
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
有点小意思的题
观察一个二叉搜索树,一个根节点,左子树,右子树……下面的递归,所以可以想到用递推的思路解决
每个二叉树的情况就是左子树的种类乘以右子树的种类
end
class Solution {
public:
int dp[100006];
void count(){
memset(dp,0,sizeof(dp));
dp[0]=1;
dp[1]=1;
for(int i=2;i<=1000;i++){
for(int j=0;j<i;j++)
dp[i]+=dp[j]*dp[i-j-1];
}
}
int numTrees(int n) {
count();
return dp[n];
}
};