Loading

【leetcode】96. Unique Binary Search Trees

Given an integer n, return the number of structurally unique BST's (binary search trees) which has exactly n nodes of unique values from 1 to n.

一般如果只需要求种类数的话,利用动态规划就可以,需要求具体的bst的话就得用递归了,本题重点就是找到种类数随节点增加的规律,如果不知道这个规律,状态转移方程就不好写。

卡特兰数:https://zhuanlan.zhihu.com/p/97619085

class Solution {
public:
    int numTrees(int n) {
        // 返回这个数值的话 感觉动态规划 比较合适?
        //那递推公式 如何求呢?
        // 题目的基本解法判断是正确的 但是没求出来递推公式
        // 本题考察了 卡特兰数
        vector<int>dp(n+1);
        dp[0]=dp[1]=1;
        for(int i=2;i<=n;++i){
            for(int j=0;j<i;++j){
                dp[i]+=dp[j]*dp[i-j-1];
            }
        }
        return dp[n];
    }
};

 

posted @ 2021-11-19 16:47  aalanwyr  阅读(23)  评论(0编辑  收藏  举报