简体   繁体   English

如何计算DFS算法的时间复杂度?

[英]How to calculate time complexity of DFS algorithm?

Like the function below, how to calculate its time complexity? 像下面的函数一样,如何计算其时间复杂度? I think it's should be O(m*n)... 我认为应该是O(m * n)...

int uniquePaths(int m, int n) {
    if (m < 1 || n < 1) return 0;     
    if (m == 1 && n == 1) return 1;      
    return uniquePaths(m - 1, n) + uniquePaths(m, n - 1);
}

You can model the time complexity with the recursive function T(m,n) = T(m-1, n) + T(m, n-1) , where T(1,1)=1 and T(m,n)=0 whenever min(m,n)<1 . 您可以使用递归函数T(m,n) = T(m-1, n) + T(m, n-1)建模时间复杂度,其中T(1,1)=1T(m,n)=0每当min(m,n)<1

It looks like T(m,n)=(m+n choose m) . 看起来像T(m,n)=(m+n choose m) To see this note that (m+n choose n) = (m+n-1 choose m) + (m+n-1 choose m-1) by the recurrence for the binomial coefficients , and that T(m,n) = T(m-1, n) + T(m,n-1) is exactly the same recurrence. 可以看到,通过二项式系数递归(m+n choose n) = (m+n-1 choose m) + (m+n-1 choose m-1) ,并且T(m,n) = T(m-1, n) + T(m,n-1)完全相同。

Thus T(m,n) = O((m+n)^n / n!) . 因此T(m,n) = O((m+n)^n / n!) (There are many other bounds .) (还有许多其他界限 。)

The Recursion Tree: 递归树:

To represent a problem with m = M and n = N, let's write it as <M, N> . 为了表示m = M和n = N的问题,我们将其写为<M, N> If we try to draw the recursion tree of this problem: 如果我们尝试绘制此问题的递归树:

  • At root, we have one problem: <M, N> 从根本上讲,我们有一个问题: <M, N>
  • Then, root breaks to two problems: <M-1, N> and <M, N-1> 然后,root打破了两个问题: <M-1, N><M, N-1>
  • And, if we continue down this recursion tree, we will reach to leaves, which will be <0, 0> . 而且,如果我们继续沿递归树向下移动,将到达<0, 0>叶子。

Tree's Depth: 树的深度:

But, what is the maximum depth possible for this tree? 但是,这棵树最大可能的深度是多少? It's 1 (M + N). 1 (M + N)。 Further, each node <M, N> can break to at most 2 paths, viz. 此外, 每个节点<M, N>可以中断至多两条路径,即。 <M-1, N> and <M, N-1> . <M-1, N><M, N-1>


Inferring Complexity From Tree: 从树推断复杂度:

So, what is the maximum number of leaves possible? 那么,最大可能的叶子数是多少? (Hint: 2 (M + N) ) (提示:2 (M + N)

Well, since every node breaks to two nodes, at every level, the number of leaves will be multiplied by 2, starting from 1 at the root. 好吧,由于每个节点都分解为两个节点,所以在每个级别上,叶子的数量将乘以2,从根的1开始。

  • So, starting from root, total leaves possible = 2 (M + N - 1) . 因此,从根开始,总数可能为2 (M + N-1)
  • Multiplying and dividing by 2 gives us, (1 / 2) * 2 (M + N) 乘以除以2得到(1/2)* 2 (M + N)
  • Getting rid of the constant value (1 / 2) gives us the complexity = 2 (M + N) ! 摆脱常数值(1/2),我们得到的复杂度= 2 (M + N)

Hence, the complexity of your algorithm can be upper bounded to O(2 (m + n) ). 因此,算法的复杂度可以上限为O(2 (m + n) )。


1 The longest path will start from <M, N> and first go to <0, N> . 1最长的路径将从<M, N> ,首先到<0, N> Then from there it will go to <0, 0> . 然后从那里转到<0, 0> So, longest possible path length = M + N. 因此,最长可能的路径长度= M +N。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM