Unique Binary Search Tree
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
分析:这道题的关键是找出规律,可以举几个例子帮助理解,化抽象为具体。实际上就是左子树书目*右子树的数目。此题用递归和循环都可以。用递归注意超时哦,此题我用的是循环。
class Solution { public: int numTrees(int n) { int sum=0; if(n<=1) return n; int* num=new int[n+1]; num[0]=1; num[1]=1; for(int i=2;i<=n;++i) { num[i]=0; for(int k=0;k<i;++k) { int left=num[k];//保存左子树的数目 int right=num[i-k-1];//保存右子树的数目 num[i]+=left*right; } } sum=num[n]; delete[] num; return sum; } };
python实现:
class Solution: # @return an integer def numTrees(self, n): if n<=1: return n num=[] for i in range(n+1): num.append(0) num[0]=1 num[1]=1 for j in range(2,n+1): for k in range(j): left=num[k] right=num[j-k-1] num[j]+=left*right sum=num[n] return sum