96. Unique Binary Search Trees

problem description

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

algorithm thought

和上题一个类型,简化了一点。上一题需要输出所有的结果,这里不需要结果,只需要数字。对于上一题,我们保存一棵树开始和结束的位置。来映射他的结果,但是这里不需要,因为只要树的size固定好,能生成的所有的tree的数量也就出来了。这里使用一个数组保存结果

code

algorithm analysis

算法中有两个循环,执行n²次,每次执行时间复杂度O(n),最后时间复杂度O(n²)

Last updated