1、題目描述
https://leetcode-cn.com/problems/unique-binary-search-trees/
給定一個整數 n,求以 1 ... n 爲節點組成的二叉搜索樹有多少種?
相關題:95. 不同的二叉搜索樹 II(打印出樹) https://blog.csdn.net/IOT_victor/article/details/107067866
2、代碼詳解
動態規劃
卡特蘭數 公式 https://baike.baidu.com/item/卡特蘭數
G(n)=G(0)∗G(n−1)+G(1)∗G(n−2)+...+G(n−1)∗G(0)
class Solution(object):
def numTrees(self, n):
"""
:type n: int
:rtype: int
"""
dp = [0] * (n + 1)
dp[0] = 1
dp[1] = 1
for i in range(2, n + 1):
for j in range(1, i + 1):
dp[i] += dp[j - 1] * dp[i - j]
return dp[n]
n = 3
s = Solution()
print(s.numTrees(n)) # 5
給定一個有序序列 1 ... n,爲了根據序列構建一棵二叉搜索樹。
我們可以遍歷每個數字 i,將該數字作爲樹根,1 ... (i-1) 序列將成爲左子樹,(i+1) ... n 序列將成爲右子樹。於是,我們可以遞歸地從子序列構建子樹。在上述方法中,由於根各自不同,每棵二叉樹都保證是獨特的。
定義兩個函數:
- G(n): 長度爲n的序列的不同二叉搜索樹個數。 是我們解決問題需要的函數
- F(i, n): 以i爲根的不同二叉搜索樹個數(1≤i≤n)。
邊界情況,當序列長度爲 1 (只有根)或爲 0 (空樹)時,G(0)=1,G(1)=1