算法学习

算法题--包含1~n的所有二叉搜索树的个数

2020-04-27  本文已影响0人  岁月如歌2020
image.png

0. 链接

题目链接

1. 题目

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

2. 思路2: 动态规划

dp[0] = 1

for i in range(1, n + 1):
    dp[n] += dp[i - 1] * dp[n - i]

解释:

3. 代码

# coding:utf8
class TreeNode:
    def __init__(self, val):
        self.val = val
        self.left = None
        self.right = None


class Solution:
    def numTrees(self, n: int) -> int:
        dp = [None] * (n + 1)
        dp[0] = 0
        if n == 0:
            return dp[0]

        dp[0] = 1
        for num in range(1, n + 1):
            dp[num] = 0
            for i in range(1, num + 1):
                dp[num] += dp[i - 1] * dp[num - i]

        return dp[n]


def my_test(solution, n):
    print('input: n={}, output: {}'.format(n, solution.numTrees(n)))


solution = Solution()
my_test(solution, 0)
my_test(solution, 1)
my_test(solution, 2)
my_test(solution, 3)
my_test(solution, 4)


输出结果

input: n=0, output: 0
input: n=1, output: 1
input: n=2, output: 2
input: n=3, output: 5
input: n=4, output: 14

结果

image.png
上一篇 下一篇

猜你喜欢

热点阅读