[英]What will be the complexity of this code for counting number of different BST(binary search tree)s from N nodes?
def count(n):
if n == 0 or n == 1:
return 1
else:
sum = 0
left = 0
right = 0
for x in range(1,n+1):
left = count(x-1)
right = count(n-x)
sum += left * right
return sum
I was reading this post and I wondered if no of different binary search trees from n nodes is 我正在阅读这篇文章,我想知道n个节点中是否有不同的二叉搜索树
(2n)! / ((n+1)! * n!)
(2n)! / ((n+1)! * n!)
from this post. (2n)! / ((n+1)! * n!)
来自这篇文章。
Then 然后
When you call count(n)
, it's calling each of count(0)
to count(n-1)
twice . 当你调用
count(n)
,它会调用count(0)
每一个来count(n-1)
两次 。
So I think you can write the recurrence like this: 所以我认为你可以写下这样的重现:
T(n) = 2 * sum[T(0) upto T(n-1)] + nk
where k represents the multiplication and summation part. T(n) = 2 * sum[T(0) upto T(n-1)] + nk
其中k表示乘法和求和部分。
Now consider: 现在考虑:
T(n+1) = 2 * sum[T(0) upto T(n)] + (n+1)k
= 2 * sum[T(0) upto T(n-1)] + 2T(n) + nk + k
= T(n) + 2T(n) + k
= 3T(n) + O(1)
Solving this, it appears to be of O(3^n)
complexity. 解决这个问题,似乎是
O(3^n)
复杂度。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.