标签:leetcode
链接: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;
}
};
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:leetcode
原文地址:http://blog.csdn.net/efergrehbtrj/article/details/47769673