【leetcode】Unique Binary Search Trees

来源:互联网 发布:作家 知乎 编辑:程序博客网 时间:2024/05/21 03:29

Unique Binary Search Trees

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.
这里写图片描述

这道题目提交将近10遍。。。动态规划的算法明确了,明确独特树的个数主要取决于左子树和右子树的个数的乘积就可以了
特别要注意数列的初始化!!!
C数组的初始化,我这里使用for循环做的,也可以用memset(f, 0, sizeof(f));

int numTrees(int n) {    if(n<=0) return 0;    int f[n+1];    f[0]=1;    f[1]=1;    for(int i=2;i<=n;i++)    {        f[i]=0;        for(int j=0; j<i;j++)        {              f[i]=f[i]+f[j]*f[i-j-1];           }    }    return f[n];}
0 0