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
題意:給定數n,二叉樹的結點的值分別為1,2....n。問能組成多少種不同的二叉搜索樹。
二叉搜索樹的性質為:在任一結點r的左(右)子樹中,所有結點(若存在)均小於(大於)r。更一般性的特點是:任何一棵二叉樹是二叉搜索樹,當且僅當其中序遍歷序列單調非降。
恩,一看,一想不會,好吧,又要找大神們了。
方法一:遞歸
思路:空樹和只有根節點時,也為BST。對於一點i,當其為根節點時,左子樹的節點的個數為i-1,(為1,...i-1),右子樹的個數為n-i(為,i+1,...n)。對一個根來說,唯一二叉樹的個數為左子樹結點的個數乘以右子樹的個數。而根節點可以從1到n 中選擇。
1 class Solution { 2 public: 3 int numTrees(int n) 4 { 5 if(n<=1) return 1; 6 int sum=0; 7 for(int i=1;i<=n;++i) 8 sum+=numTrees(i-1)*numTrees(n-i); 9 10 return sum; 11 } 12 };
方法二:
還有大神說這是Catalan Number卡特蘭數的一個例子。卡特蘭數的的遞推公式:
可以使用動態規划解決問題。維護向量sumNode,sumNode(i)為結點個數為i時,唯一二叉搜索樹的個數。和這題相對應的意義,可以寫出n較小的情況。
1 class Solution { 2 public: 3 int numTrees(int n) 4 { 5 vector<int> sumNode(n+1,0); 6 sumNode[0]=1; 7 sumNode[1]=1; 8 9 for(int i=2;i<=n;++i) 10 for(int j=0;j<i;++j) //j符合條件時,最大為i-1,對照公式 11 sumNode[i]+=sumNode[j]*sumNode[i-j-1]; 12 13 return sumNode[n]; 14 } 15 };