简繁EN

LeetCodeNo. 106

【LeetCode with Python】 96. Unique Binary Search Trees

目錄

題目

原題頁面:https://leetcode.com/problems/unique-binary-search-trees/
題目型別:Tree, Dynamic Programming
難度評價:Medium
類似題目:(M) Unique Binary Search Trees II

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
2
3
4
5
1         3     3      2      1
\ / / / \ \
3 2 1 1 3 2
/ / \ \
2 1 2 3

分析

給點節點數,求出能構造出符合二叉搜尋樹定義的二叉樹數量。
二叉搜尋樹的根選定以後,左子樹只能放比根小的值,右子樹只能放比根大的值,所以能構成多少種形狀只取決於節點個數。直接遞迴搜尋的話,假設當前子樹可分配節點數為n,就列舉每一種分配方案(子樹根節點佔用一個,左子樹分配0個節點、右子樹分配n-1個結點,然後左子樹1個、右子樹n-2個……直到左子樹n-1個、右子樹0個),再對左右子樹繼續遞迴。
問題是算過的子問題不記錄,同一個子問題會被反覆求解。算n個節點時,0到n-1個節點的每個子問題都要直接遞迴呼叫兩次(一次當左子樹、一次當右子樹),所以每多一個節點,總的呼叫次數就變成原來的3倍。所以用DP來做。
我用counts[i]記i個節點能構成的不同二叉搜尋樹的數量,空樹也算一種,所以counts[0]=1。有nodes個節點時,左子樹分left個,右子樹分right=nodes-left-1個。左右子樹的形狀互相獨立,這種分法就有counts[left]×counts[right]種。所有分法加起來就是counts[nodes]。
從counts[1]一直算到counts[n],算每一項只用到比它小的項,它們都已經算好了。卡特蘭數就是用同一個遞推定義的,第0項也是1,所以counts[n]就是第n個卡特蘭數。兩層迴圈,內層列舉left,一共執行1+2+...+n=n(n+1)/2次,時間複雜度O(n^2)。空間只有一個長n+1的counts陣列,O(n)。


程式碼

1
2
3
4
5
6
7
8
9
10
class Solution:
# @return an integer
def numTrees(self, n):
counts = [0 for i in range(0, n + 1)] # counts[i]: unique BSTs with i nodes
counts[0] = 1
for nodes in range(1, n + 1):
for left in range(0, nodes):
right = nodes - left - 1 # 1 as the sub-root node
counts[nodes] += counts[left] * counts[right]
return counts[n]

本文地址:https://xnerv.wang/zh-tw/leetcode-unique-binary-search-trees/