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 的所有可能就是 。将所有 root 的可能性再加起来就是 n 个节点的所能组成 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]

你可能感兴趣的:(163. Unique Binary Search Trees)