title: 算法小練——不同的二叉搜索樹
abbrlink: 4096678489
date: 2020-01-12 21:39:51
categories:
tags:
不同的二叉搜索樹
描述
給定一個整數 n,求以 1 … n 爲節點組成的二叉搜索樹有多少種?
示例
輸入: 3
輸出: 5
解釋:
給定 n = 3, 一共有 5 種不同結構的二叉搜索樹:
1 3 3 2 1
\ / / / \ \
3 2 1 1 3 2
/ / \ \
2 1 2 3
代碼
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];
}
}
作者:LeetCode
鏈接:https://leetcode-cn.com/problems/unique-binary-search-trees/solution/bu-tong-de-er-cha-sou-suo-shu-by-leetcode/
來源:力扣(LeetCode)
著作權歸作者所有。商業轉載請聯繫作者獲得授權,非商業轉載請註明出處。
代碼2
class Solution {
public int numTrees(int n) {
// Note: we should use long here instead of int, otherwise overflow
long C = 1;
for (int i = 0; i < n; ++i) {
C = C * 2 * (2 * i + 1) / (i + 2);
}
return (int) C;
}
}
作者:LeetCode
鏈接:https://leetcode-cn.com/problems/unique-binary-search-trees/solution/bu-tong-de-er-cha-sou-suo-shu-by-leetcode/
來源:力扣(LeetCode)
著作權歸作者所有。商業轉載請聯繫作者獲得授權,非商業轉載請註明出處。
筆記
舉例而言,F(3, 7)F(3,7),以 3 爲根的不同二叉搜索樹個數。爲了以 3 爲根從序列 [1, 2, 3, 4, 5, 6, 7] 構建二叉搜索樹,我們需要從左子序列 [1, 2] 構建左子樹,從右子序列 [4, 5, 6, 7] 構建右子樹,然後將它們組合(即笛卡爾積)。
巧妙之處在於,我們可以將 [1,2] 構建不同左子樹的數量表示爲 G(2)G(2), 從 [4, 5, 6, 7]` 構建不同右子樹的數量表示爲 G(4)G(4)。這是由於 G(n)G(n) 和序列的內容無關,只和序列的長度有關。於是,F(3,7) = G(2) \cdot G(4)F(3,7)=G(2)⋅G(4)。