算法训练:Unique Binary Search Trees

来源:互联网 发布:三国志9优化伴侣是什么 编辑:程序博客网 时间:2024/06/03 18:05

题目链接: https://leetcode.com/problems/binary-tree-level-order-traversal/#/description


题目描述:

       假定节点数为n,要求返回二叉搜索树的个数。

       例如:n=3时,二叉搜索树如下所示,所以返回值为5。

       1         3     3      2      1        \         /      /      / \       \         3     2     1      1  3      2         /     /        \                   \        2    1        2                   3

解题思路:

     采用的DP方法,用result[i]来保存有i个节点的二叉搜索树的个数。

     状态转移方程:result[i]=result[j]*result[i-j-1],其中j相当于左子树的节点个数,取值0到i-1。

    int numTrees(int n) {        if(n<=0) return 0;    vector<int>result(n,0);    result[0] = 1;    result[1] = 1;    //遍历节点数为2到n的情况    //result[i]为具有i个节点时二叉搜索树的个数    for(int i=2;i<=n;i++)    {        //j为左子树的节点个数    for(int j=0;j<i;j++)    {    result[i] += result[j]*result[i-j-1];    }    }    return result[n];     }

运行结果:

Your Input
5
Your answer
42
Expected answer
42











0 0
原创粉丝点击