标签:
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
int numTrees(int n) { if (n<=0) return 0; if (n==1) return 1; if (n==2) return 2; vector<int>a(n+1,0); a[0]=1; a[1]=1; a[2]=2; for (int i=3;i<=n;i++) { int temp=0; for (int j=0;j<i;j++) { temp+=a[j]*a[i-j-1]; } a[i]=temp; } return a[n]; }方法二:
int numTrees1(int n) { if (n<=0) return 0; if (n==1) return 1; if (n==2) return 2; unsigned long c1=fac(2*n); unsigned long c=fac(n); int res=c1/(c*c*(n+1)); return res; } unsigned long fac(int n) { vector<unsigned long> a(n+1,1); a[0]=1; a[1]=1; for (int i=2;i<=n;i++) { a[i]=i*a[i-1]; } return a[n]; }
#include <iostream> #include <vector> using namespace std; int numTrees(int n); int numTrees1(int n); unsigned long fac(int n); void main() { int n=11; cout<<numTrees(n)<<endl; for (int i=1;i<10;i++) { cout<<numTrees1(i)<<endl;//从1到9输出第二种方法的结果 } } int numTrees(int n) { if (n<=0) return 0; if (n==1) return 1; if (n==2) return 2; vector<int>a(n+1,0); a[0]=1; a[1]=1; a[2]=2; for (int i=3;i<=n;i++) { int temp=0; for (int j=0;j<i;j++) { temp+=a[j]*a[i-j-1]; } a[i]=temp; } return a[n]; } int numTrees1(int n) { if (n<=0) return 0; if (n==1) return 1; if (n==2) return 2; unsigned long c1=fac(2*n); unsigned long c=fac(n); int res=c1/(c*c*(n+1)); return res; } unsigned long fac(int n) { vector<unsigned long> a(n+1,1); a[0]=1; a[1]=1; for (int i=2;i<=n;i++) { a[i]=i*a[i-1]; } return a[n]; }结果如下:
leetcode-Unique Binary Search Trees:
标签:
原文地址:http://blog.csdn.net/sinat_24520925/article/details/45562273