90_leetcode_Unique Binary Search Trees

来源:互联网 发布:centos 7.3 lnmp 编辑:程序博客网 时间:2024/04/28 21:16

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.

1:特殊情况;2:new和delete数组;3:f(n) = f(0) *f(n-1) + f(1) * f(n-2) +......+ f(n-1) * f(0);


    int numTrees(int n)    {        if(n < 0)        {            return 0;        }        if(n <= 2)        {            return n;        }                int *A = new int[n+1];        memset(A,0, n +1);                A[0] = 1;        A[1] = 1;        A[2] = 2;                int result = 0;                for(int i = 3; i <= n; i++)        {            result = 0;            for(int j = 0; j < i; j++)            {                result += A[j] * A[i-1-j];            }            A[i] = result;        }                result = A[n];                delete[] A;                return result;    }


0 0
原创粉丝点击