什么是这个天真code来计算组合的大O的复杂性?

编程入门 行业动态 更新时间:2024-10-19 19:37:14
本文介绍了什么是这个天真code来计算组合的大O的复杂性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

下面的递归算法是(效率非常低)的方式来计算ñ选择K:

The following recursive algorithm is a (fairly inefficient) way to compute n choose k:

int combinationsOf(int n, int k) { if (k == 0) return 1; if (n == 0) return 0; return combinationsOf(n - 1, k) + combinationsOf(n - 1, k - 1); }

它是基于以下递归洞察:

It is based on the following recursive insight:

其实评价这一函数的函数调用了很多。例如,计算2选2这种方式使这些调用:

Actually evaluating this function takes a LOT of function calls. For example, computing 2 choose 2 this way makes these calls:

combinationsOf(2, 2) | | | +- combinationsOf(1, 2) | | | | | +- combinationsOf(0, 2) | | | +-- combinationsOf(1, 1) | | | | | +- combinationsOf(0, 1) | | | +- combinationsOf(1, 0) +- combinationsOf(2, 1) | | | +- combinationsOf(2, 0) | +- combinationsOf(1, 1) | | | +- combinationsOf(0, 1) | +- combinationsOf(1, 0)

有许多的方法来改善该功能的运行时 - 我们可以使用动态编程,使用闭合形式的式NCK =正! /(K(N - !K))等。但是,我很好奇,刚才的如何的低效率这个特殊的算法

There are many ways to improve the runtime of this function - we could use dynamic programming, use the closed-form formula nCk = n! / (k! (n - k)!), etc. However, I am curious just how inefficient this particular algorithm is.

这是什么功能的大O的时间复杂性,n和k的函数?

What is the big-O time complexity of this function, as a function of n and k?

推荐答案

让 C(N,K)是计算成本 binom( N,K)以这种方式,以

Let C(n,k) be the cost of computing binom(n,k) in that way, with

C(0,_) = 1 C(_,0) = 1

作为基础的情况下。

as base cases.

复发显然是

C(n,k) = 1 + C(n-1,k-1) + C(n-1,k)

如果我们把除了拥有成本1。然后,我们可以很容易地检查

if we take addition to have cost 1. Then, we can easily check that

k C(n,k) = 2 * ∑ binom(n,j) - 1 j=0

感应。

因此​​,对于 K> = N ,成本 2 ^(N + 1) - 1 , C(N,N-1)= 2 ^(N + 1) - 3 , C(N,1)= 2 * N + 1 , C(N,2)= N *(N + 1)+1 ,(而除此之外,我没有看到整齐的公式)。

So for k >= n, the cost is 2^(n+1) - 1, C(n,n-1) = 2^(n+1)- 3, C(n,1) = 2*n+1, C(n,2) = n*(n+1)+1, (and beyond that, I don't see neat formulae).

我们有明显的上界

C(n,k) < 2^(n+1)

独立 K ,以及 K&LT; N / 2 我们可以粗略估算

independent of k, and for k < n/2 we can coarsely estimate

C(n,k) <= 2*(k+1)*binom(n,k)

这给小得多界小 K ,所以总体

C(n,k) ∈ O(min{(k+1)*binom(n,min(k, n/2)), 2^n})

(需要夹紧 K 的最低,因为 binom(N,K)减小回1为 K&GT; N / 2 )

(need to clamp the k for the minimum, since binom(n,k) decreases back to 1 for k > n/2).

更多推荐

什么是这个天真code来计算组合的大O的复杂性?

本文发布于:2023-11-30 19:55:39,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1651309.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:组合   复杂性   天真   code

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!