求解递归关系T(n)= T(n-1)* T(n-2)+ c其中T(0)= 1且T(1)= 2

时间:2016-05-13 14:27:37

标签: algorithm time-complexity recurrence

我需要解决

的递归关系
T(n) = T(n - 1) * T(n - 2) + c    where T(0) = 1 and T(1) = 2. 

该算法计算2 f(n)其中f(n)是n th Fibonacci数。我假设T(n - 2)大约等于T(n - 1)然后我重写关系为

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

和终结我达到了O(n)的复杂性。这个算法:

Power(n):
    if n == 0 then x = 1;
    else if n == 1 then x = 2;
    else x = Power(n - 1) * Power(n - 2);
    return x;

递归关系T(n)= T(n - 1)* T(n - 2)+ c是否具有O(n)复杂度?

2 个答案:

答案 0 :(得分:2)

您在算法中使用递归关系中的乘法混淆了。您计算Power(n - 1)Power(n - 2)并将它们相乘,但这不会花费T(n - 1) * T(n - 2)时间。这些值是单独计算的,然后乘以T(n - 1) + T(n - 2)时间,假设是恒定时间乘法。

然后重现变为T(n) = T(n - 1) + T(n - 2) + c。我们将通过替换解决这个问题。我会跳过选择n 0 ;我们的归纳假设将是T(n) = d * 2^n - 1。 (我们需要-1来允许稍后取消c;这称为强化归纳假设,参见例如here)。

T(n) = T(n - 1) + T(n - 2) + c
     = d * (2^(n - 1) - 1) + d * (2^(n - 2) - 1) + c    (substitute by IH)
     = 3d * 2^(n - 2) - 2d + c
    <= d * 2^n - 2d + c                                 (3 < 2^2)
    <= d * 2^n                                          (when d > c / 2)

结论:T(n)∈O(2 n )。

额外事实:紧束缚实际上是Θ(φ n ),其中φ是黄金比率。有关说明,请参阅this answer

答案 1 :(得分:1)

首先,对于某些T(n) = T(n-1) + T(n-2) + C,为T(1) = T(0) = 1 C>0建模的运行时间为n-1。这是因为您进行了两次递归调用,一次在n-2上,另一次在C上。

如果我们忘记了额外的常量(最后贡献了一个因子T(n) = Theta(1.618... ^ n)),那么你的复发恰好是Fibonacci recurrence。确切的解决方案是这个(图像来源:维基百科):

enter image description here

,其中

enter image description here

enter image description here

你可以说<?php if(!empty($_GET['country'])) { $country_url = 'https://restcountries.eu/rest/v1/name/' . urlencode($_GET['country']) . '?fullText=true'; $country_json = file_get_contents($country_url); $country_array = json_decode($country_url, true); } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset = "utf-8" /> <title> PHP Country Practice </title> </head> <body> <form action=""> <input type = "text" name = "country" /> <button type="submit">submit </button> </form> <?php if(!empty($country_array)) { echo '<p> $country_array['name'] </p>'; } ?> </body> </html>