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

0、题目分析

这道题的重点就是去寻找节点数目和BST数目的关联,而不是真的去构建一棵棵树然后去数总数

那么规律在哪里呢,我们可以利用二叉搜索树这种数据结构一个特点:子树必然也是二叉搜索树。

所以我们可以首先选定根节点,然后把一些结点放在左子树,一些结点放在右子树(当然还需要遵守BTS的限制),然后根据排列组合原则,把左子树的数目乘以右子树的数目,就能得到以该结点为根的BTS的数目,然后把所有结点都作为根节点遍历一遍就行了

递推表达式:
dp[i] += dp[j - 1] * dp[i - j];
i表示结点数,j-1表示放在左子树的结点数,i-j表示放在右子树的结点数

1、代码实现

class Solution {
public:
    int numTrees(int n) {
        vector<int> dp(n + 1, 0);
        dp[0] = 1;
        for(int i = 1; i <= n; i++){
            for(int j = 1; j <= i; j++){
                dp[i] += dp[j - 1] * dp[i - j];
            }
        }
        return dp[n];

    }
};

收藏 打印