[英]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)=1
和T(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 .) (还有许多其他界限 。)
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: 如果我们尝试绘制此问题的递归树:
<M, N>
<M, N>
<M-1, N>
and <M, N-1>
<M-1, N>
和<M, N-1>
<0, 0>
. <0, 0>
叶子。 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>
。
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开始。
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.