[LeetCode] Unique Binary Search Tree

时间:2023-03-10 00:46:09
[LeetCode] Unique Binary Search Tree

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

解题思路:

设有n个结点的二叉查找树有b[n]个,则设想对一个排好序的list,我们从第一个元素开始枚举根节点。对于每一个根节点,这棵二叉查找树的可能是b[left] * b[right], left < n, right < n。

故我们只需要取b[0] = 0, b[1] = 1, 然后迭代计算b[i]即可。

class Solution {
public:
int numTrees(int n) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
if(n == )
return ; int *num;
num = new int[n + ];
num[] = ;
num[] = ;
for(int i = ;i <= n;i++)
{
num[i] = ;
for(int j = ;j < i;j++)
num[i] += num[j] * num[i - - j];
} return num[n];
}
};