以下代码的时间复杂度为O(2 ^ n),请您解释一下为什么?
int f(int n)
{
if (n == 1)
return 1;
return 1 + f(f(n-1));
}
提前致谢
答案 0 :(得分:1)
f(n)= n是这种复原关系的解决方案
证明: f(n)= f(f(n-1))+ 1 = f(n-1)+ 1 =(n-1)+ 1 = n
验证它的示例VBA代码:
Sub test()
For i = 1 To 20
Debug.Print i, f(i)
Next
End Sub
Function f(ByVal n As Long) As Long
If n = 1 Then
f = 1
Else
f = 1 + f(f(n - 1))
End If
End Function
由于我们已经确定f(n)= n,我们可以得出结论
f(n-1)= n-1
假设需要An
次调用才能得到f(n),An
是一个递归关系:
An = 1 + 2 * An-1
递归关系的解是2 ^ n - 1
答案 1 :(得分:0)
成本复杂度为2 ^ n -1
VBA代码:
选项明确 Dim count As Long
Sub test()
Dim i As Integer
For i = 1 To 20
count = 0
f i
Debug.Print i, count
Next
End Sub
Function f(ByVal n As Long) As Long
count = count + 1
If n = 1 Then
f = 1
Else
f = 1 + f(f(n - 1))
End If
End Function
输出:
1 1
2 3
3 7
4 15
5 31
6 63
7 127
8 255
9 511
10 1023
11 2047
12 4095
13 8191
14 16383
15 32767
16 65535
17 131071
18 262143
19 524287
20 1048575