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
题意:
求1-n组成的二叉排序树的个数。
思路:
设h(n)为1-n的二叉排序树个数,那么可以在二叉排序树中左边放0个,右边放n-1个,左边放一个,右边放n-2个,以此类推,那么h(N)=h(0)*h(n-1)+……h(n-1)*h(0)。
拓展:h(N)即使卡特兰数。
代码:
class Solution {
public:
int numTrees(int n) {
long long dp[n+1];
dp[0]=1;
for(int i=1;i<=n;i++)
dp[i]=((4*i-2)*dp[i-1]/(i+1));
return (int)dp[n];
}
};
卡特兰数的应用