题目:
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
思路:
动态规划:dp[i]表示有多少种。
已知n, 任意取k作为根节点( 1 <= k <= n),那么k左边有k-1个节点,有dp[k - 1]种组合的方式。同理右边有dp[n - k]种。
代码:
int numTrees(int n) {
vector<int> ans(n + 1, 0);
ans[0] = 1;
ans[1] = 1;
ans[2] = 2;
for(int i = 3; i < n + 1; i++)
for(int k = 1; k <= i; k++)
ans[i] += ans[k - 1] * ans[i - k];
return ans[n];
}
总结:
这道题主要考察了对二叉搜索树的熟悉程度。