[一起来刷leetcode吧][20]--No.96 Unique Binary Search Trees

本文解析了LeetCode上的第96题“Unique Binary Search Trees”,介绍了如何使用Catalan数来解决该问题,并提供了一段Python代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这篇文章是程序自动发表的,详情可以见 这里
href="http://ounix1xcw.bkt.clouddn.com/github.markdown.css" rel="stylesheet">

这是leetcode的第96题--Unique Binary Search Trees

  题目 Given n, how many structurally unique BST's (binary search trees) that store values 1...n?   思路 注意到给定一棵树,只有一种对应的BST(1,2,...,n)。所以这道题就使求N个节点能形成多少种不同的树,就很简单了,直接用Catalan数C(n2n)/(1 n),不过在计算中我优化了一下,而且注意最后结果用了round,不能直接用int(),这会截断小数的   

show me the code

class Solution(object):
    def numTrees(self, n):
        """
        :type n: int
        :rtype: int
        """
        rst = 1
        for i in range(2,n 1):
            rst *=(n i)*1.0/i
        return int(round(rst))
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值