163. Unique Binary Search Trees

題目

https://www.lintcode.com/problem/unique-binary-search-trees/description?_from=ladder&&fromId=2

實現

首先考慮 n = 3 的情況,假如現在的節點是 1, 2, 3 那麼我們以每個節點作爲 root 來想:

以 1 爲 root:

1
  \
   xxx

以 2 爲 root:

     2
   /   \
xxx     yyy

以 3 爲 root:

    3
  /
xxx

其中 xxx,yyy 都是子樹的所有可能(子樹爲空就是可能數爲 1),推廣一下,對於當前 root 的所有可能就是 xxx \times yyy。將所有 root 的可能性再加起來就是 n 個節點的所能組成 BST 的可能性,即

總BST數=以1爲root所組成BST數+以2爲root所組成BST數+...+以n爲root所組成BST數

爲了可以重用之前所使用過的結果,所以可以用數組來存,即 array[x]=y 就表示 x 個節點時所能組成的 BST 數爲 y。

代碼

class Solution:
    """
    @param n: An integer
    @return: An integer
    """
    def numTrees(self, n):
        dp = [1, 1, 2]
        if n <= 2:
            return dp[n]
        else:
            dp += [0 for i in range(n - 2)]

            for i in range(3, n + 1):
                # 左邊節點數
                for j in range(1, i + 1):
                    dp[i] += dp[j - 1] * dp[i - j]

            return dp[n]
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章