96Unique Binary Search Trees

来源:互联网 发布:知乎上面的神回复 编辑:程序博客网 时间:2024/05/01 07:53

96 Unique Binary Search Trees

链接:https://leetcode.com/problems/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.

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

Hide Tags Tree Dynamic Programming

给出一个数字n,求1—n,n个数字生成称多少种二叉搜索树。n个数组生成二叉树的数量可以慢慢分解为n-1,n-2,n-3……1能生成多少二叉树。

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