Introduction: the solution of time complexity is explained here by examples, which can be understood by readers. All of the following cases are written in Python!
Case 1: Calculate the Npower of
The Code is as follows:
Def exp1 (A, n ):
If n = 1:
Return
Else:
Return a * exp2 (A, n-1)
Analysis: 1. The problem scale is N; 2. When the scale is 1, it ends; 3. Suppose T (n) represents the number of steps required for the problem where the scale is N;
Solution:
T (n) = 3 + T (n-1) // Note: 3 represents the number of operations in a loop, and the comparison of IF is "= ", the second operation is the "-" in n-1 in recursion, and the third operation is the "*" in a * exp1 (A, n-1). Each time the scale is reduced, the above three operations are performed.
Decomposition: T (n) = 3 + 3 + T (n-2)
= 3 + 3 + 3 + T (n-3)
......
= 3 * k + T (n-k)
When the scale is 1, the returned result is n-k = 1-"K = n-1, bringing K into T (N)
T (n) = 3 (n-1) + T (1) = 3n-3 + 2 = 3n-1 // Note: When T (1) is 1, two operations are performed.
To sum up, the time complexity of the above procedures is: O (n)
This article from the "heaven reward diligence" blog, please be sure to keep this source http://737110312.blog.51cto.com/2927801/1441502
Time complexity of Recursive Algorithms