1. 程式人生 > >LeetCode 96. Unique Binary Search Trees (獨立二叉搜尋樹)

LeetCode 96. Unique Binary Search Trees (獨立二叉搜尋樹)

原題

Given n, how many structurally unique BST’s (binary search trees) that store values 1 … n?

Example:

Input: 3
Output: 5
Explanation:
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

Reference Answer

思路分析

首先明確n個不等的數它們能構成的二叉搜尋樹的種類都是相等的。而且1到n都可以作為二叉搜尋樹的根節點,當k是根節點時,它的左邊有k-1個不等的數,它的右邊有n-k個不等的數。以k為根節點的二叉搜尋樹的種類就是左右可能的種類的乘積。用遞推式表示就是 h ( n ) =

h ( 0 ) h ( n 1 )
+ h ( 1 ) h ( n 2 ) + . . . + h ( n 1 ) h ( 0 ) ( n > = 2 ) h(n) = h(0)*h(n-1) + h(1)*h(n-2) + ... + h(n-1)h(0) (其中n>=2) ,其中h(0)=h(1)=1,因為0個或者1個數能組成的形狀都只有一個。從1到n依次算出h(x)的值即可。此外這其實就是一個卡特蘭數,可以直接用數學公式計算,不過上面的方法更加直觀一些。

Reference Code

class Solution:
    def numTrees(self, n):
        """
        :type n: int
        :rtype: int
        """
#         if n == 0 or n == 1:
#             return 1
#         elif n == 2:
#             return 2
#         else:
#             res = 0
#             for i in range(n):
#                 res += self.numTrees(i) * self.numTrees(n-i-1)
#             return res
        res = [1,1]
        for i in range(2,n+1):
            count = 0
            for j in range(i):
                count += res[j] * res[i-j-1]
            res.append(count)
        return res[-1]

Note:

  1. 動態規劃的使用主要難點在於遞迴公式的尋找,如本題 h ( n ) = h ( 0 ) h ( n 1 ) + h ( 1 ) h ( n 2 ) + . . . + h ( n 1 ) h ( 0 ) ( n > = 2 ) h(n) = h(0)*h(n-1) + h(1)*h(n-2) + ... + h(n-1)h(0) (其中n>=2)

參考文獻

[1] https://shenjie1993.gitbooks.io/leetcode-python/096 Unique Binary Search Trees.html