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個結點的二叉搜索樹,求一共有多少個不一樣類型的二叉搜索樹。spa
當n=1時,只有1個根節點,則只能組成1種形態的二叉樹,令n個節點可組成的二叉樹數量表示爲h(n),則h(1)=1; h(0)=0; 當n=2時,1個根節點固定,還有2-1個節點。這一個節點能夠分紅(1,0),(0,1)兩組。即左邊放1個,右邊放0個;或者左邊放0個,右邊放1個。即:h(2)=h(0)*h(1)+h(1)*h(0)=2,則能組成2種形態的二叉樹。 當n=3時,1個根節點固定,還有2個節點。這2個節點能夠分紅(2,0),(1,1),(0,2)3組。即h(3)=h(0)*h(2)+h(1)*h(1)+h(2)*h(0)=5,則能組成5種形態的二叉樹。 以此類推,當n>=2時,可組成的二叉樹數量爲h(n)=h(0)*h(n-1)+h(1)*h(n-2)+...+h(n-1)*h(0)種,即符合Catalan數的定義,可直接利用通項公式得出結果。 令h(1)=1,h(0)=1,catalan數(卡特蘭數)知足遞歸式: h(n)= h(0)*h(n-1)+h(1)*h(n-2) + ... + h(n-1)h(0) (其中n>=2) 另類遞歸式: h(n)=((4*n-2)/(n+1))*h(n-1); 該遞推關係的解爲: h(n)=C(2n,n)/(n+1) (n=1,2,3,...)
遞推公式
f(k)*f(n-1-k):f(k)表示根結點左子樹有k個結點,其有的形狀是f(k),f(n-1-k)表示右子樹有n-1-k個結點
f(n) = 2*f(n-1) + f(1)*f(n-2) + f(2)*f(n-3) + f(3)*f(n-4) + … +f(n-2)*f(1).net
算法實現類code
public class Solution { public int numTrees(int n) { if (n <= 0) { return 0; } else if (n == 1) { return 1; } int[] result = new int[n + 1]; result[0] = 0; result[1] = 1; // 求f(2)...f(n) for (int i = 2; i <= n; i++) { // 求f(i) result[i] = 2 * result[i - 1]; for (int j = 1; j <= i - 1 ; j++) { result[i] += result[j]*result[i - 1 -j]; } } return result[n]; } }