递归算法的复杂度计算(常用的递归方程求解)

递归(recursion)算法的运行时间常用递归表达式表示。本文主要讲解如何从递归表达式求解出bigO时间复杂度。

例一:

T(n) = T(n-1)+1

解:T(n) = T(n-1)+1 = [T(n-2)+1]+1 = T(n-2)+2 = T(n-3)+3 = … = T(n-n)+n = n

故 O(n) = n

例二:

T(n) = T(n-1)+n-1

解:T(n) = T(n-1)+n-1 = T(n-2)+(n-2)+(n-1) = T(n-3)+(n-3)+(n-2)+(n-1) = …

= T(n-(n-1))+n-(n-1)+…+(n-2)+(n-1) = 0+1+2+3+4+…+(n-1) = n(n-1)/2

故 O(n) = n^2

例三:

T(n) = 2T(n-1)+1

解:T(n) = 2T(n-1)+1 =  2( 2T(n-2)+1)+1 = 4T(n-2)+2+1 = …

= 2^(n-1)T(n-(n-1))+2^(n-2)+…2^2+2+1 = 2^(n-1)+2^(n-2)+…2^2+2+1=2^n-1

故O(n) = 2^n

例四:

T(n) = 2T(n/2)+n-1

解: T(n) = 2T(n/2)+n-1 = T(n) = 2(T(n) = 2T(n/4)+n/2-1)+n-1 = 4T(n/4)+2n-2-1 = 4(2T(n/8)+n/4-1)+2n-2-1

= 8T(n/8)+3n-4-2-1 = 2^k(T(n/(2^k)))+kn-2^(k-1)-…-4-2-1

令n=2^k

代入得:T(n) = (2^k)T(1)+k(2^k)-(2^(k-1)+…+4+2+1) = k(2^k)-((2^k)-1) = n(logn)-n+1 

故 O(n)= n(logn)

总结以上四个常用递归关系表达式,其他的万变不离其宗了。

    原文作者:递归算法
    原文地址: https://blog.csdn.net/huangyongtao2016/article/details/70174558
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞