给定一个值n,能构建出多少不同的值包含1...n的二叉搜索树(BST)?
例如
给定 n = 3, 有五种不同的二叉搜索树(BST)
public class Solution { public int numTrees(int n) { int[] G = new int[n + 1]; G[0] = 1; G[1] = 1; for (int i = 2; i <= n; ++i) { for (int j = 1; j <= i; ++j) { G[i] += G[j - 1] * G[i - j]; } } return G[n]; } }
public class Solution { public int numTrees(int n) { long Catalan = 1; for(int i = 0; i < n; i++){ Catalan = 2*(2*i+1)*Catalan/(i+2); } return (int)Catalan; } }
//递归 递推公式:f(n) = f(i)*f(n-i) +... (i=0),f(0) = 1; public int numTrees (int n) { if (n == 0){ return 1; } int d = 0; for (int i = 0; i < n; i++) { d += numTrees(i)*numTrees(n-i-1); } return d; } //循环 public int numTrees (int n) { int[] d = new int[n+1]; d[0] = 1; d[1] = 1; for (int i = 2; i < n+1; i++) { for (int j = 0; j < i; j++) { d[i] += d[j]*d[i-j-1]; } } return d[n]; }
/** 卡特兰数(Catalan)的应用 */ public class Solution { public int numTrees(int n) { if (n == 0 || n == 1) return 1; int[] result = new int[n+1]; result[0] = result[1] = 1; //result[n] = result[0]*result[n-1] + result[1]*result[n-2] + ... // + result[n-1]result[0]; for (int i = 2; i <= n; i++) for (int j = 0; j <= i-1; j++) result[i] += result[j]*result[i-j-1]; return result[n]; } }
/** * Taking 1~n as root respectively: * 1 as root: # of trees = F(0) * F(n-1) // F(0) == 1 * 2 as root: # of trees = F(1) * F(n-2) * 3 as root: # of trees = F(2) * F(n-3) * ... * n-1 as root: # of trees = F(n-2) * F(1) * n as root: # of trees = F(n-1) * F(0) * * So, the formulation is: * F(n) = F(0) * F(n-1) + F(1) * F(n-2) + F(2) * F(n-3) + ... + F(n-2) * F(1) + F(n-1) * F(0) */ int numTrees(int n) { int dp[n+1]; dp[0] = dp[1] = 1; for (int i=2; i<=n; i++) { dp[i] = 0; for (int j=1; j<=i; j++) { dp[i] += dp[j-1] * dp[i-j]; } } return dp[n]; }