`

程序员面试题精选(16)-O(logn)求Fibonacci数列

阅读更多

题目:定义Fibonacci数列如下:          /   0                       n=0
f(n)=       1                       n=1
         \   f(n-1)+f(n-2)           n=2
输入n,用最快的方法求该数列的第n项。
分析:在很多C语言教科书中讲到递归函数的时候,都会用Fibonacci作为例子。因此很多程序员对这道题的递归解法非常熟悉,看到题目就能写出如下的递归求解的代码。

C++代码 复制代码
  1. ///////////////////////////////////////////////////////////////////////   
  2. // Calculate the nth item of Fibonacci Series recursively   
  3. ///////////////////////////////////////////////////////////////////////   
  4. long long Fibonacci_Solution1(unsigned int n)   
  5. {   
  6.       int result[2] = {0, 1};   
  7.       if(n < 2)   
  8.             return result[n];   
  9.   
  10.       return Fibonacci_Solution1(n - 1) + Fibonacci_Solution1(n - 2);   
  11. }  
///////////////////////////////////////////////////////////////////////
// Calculate the nth item of Fibonacci Series recursively
///////////////////////////////////////////////////////////////////////
long long Fibonacci_Solution1(unsigned int n)
{
      int result[2] = {0, 1};
      if(n < 2)
            return result[n];

      return Fibonacci_Solution1(n - 1) + Fibonacci_Solution1(n - 2);
}


但是,教科书上反复用这个题目来讲解递归函数,并不能说明递归解法最适合这道题目。我们以求解f(10)作为例子来分析递归求解的过程。要求得f(10),需要求得f(9)和f(8)。同样,要求得f(9),要先求得f(8)和f(7)……我们用树形结构来表示这种依赖关系
                   f(10)
                /         \
             f(9)          f(8)
           /      \        /     \
        f(8)      f(7)   f(6)    f(5)
       /    \      /    \
    f(7)   f(6)   f(6) f(5)
我们不难发现在这棵树中有很多结点会重复的,而且重复的结点数会随着n的增大而急剧增加。这意味这计算量会随着n的增大而急剧增大。事实上,用递归方法计算的时间复杂度是以n的指数的方式递增的。大家可以求Fibonacci的第100项试试,感受一下这样递归会慢到什么程度。在我的机器上,连续运行了一个多小时也没有出来结果。
其实改进的方法并不复杂。上述方法之所以慢是因为重复的计算太多,只要避免重复计算就行了。比如我们可以把已经得到的数列中间项保存起来,如果下次需要计算的时候我们先查找一下,如果前面已经计算过了就不用再次计算了。
更简单的办法是从下往上计算,首先根据f(0)和f(1)算出f(2),在根据f(1)和f(2)算出f(3)……依此类推就可以算出第n项了。很容易理解,这种思路的时间复杂度是O(n)。

C++代码 复制代码
  1. ///////////////////////////////////////////////////////////////////////   
  2. // Calculate the nth item of Fibonacci Series iteratively   
  3. ///////////////////////////////////////////////////////////////////////   
  4. long long Fibonacci_Solution2(unsigned n)   
  5. {   
  6.       int result[2] = {0, 1};   
  7.       if(n < 2)   
  8.             return result[n];   
  9.       long long   fibNMinusOne = 1;   
  10.       long long   fibNMinusTwo = 0;   
  11.       long long   fibN = 0;   
  12.       for(unsigned int i = 2; i <= n; ++ i)   
  13.        {   
  14.              fibN = fibNMinusOne + fibNMinusTwo;   
  15.   
  16.              fibNMinusTwo = fibNMinusOne;   
  17.              fibNMinusOne = fibN;   
  18.        }   
  19.   
  20.       return fibN;   
  21. }  
///////////////////////////////////////////////////////////////////////
// Calculate the nth item of Fibonacci Series iteratively
///////////////////////////////////////////////////////////////////////
long long Fibonacci_Solution2(unsigned n)
{
      int result[2] = {0, 1};
      if(n < 2)
            return result[n];
      long long   fibNMinusOne = 1;
      long long   fibNMinusTwo = 0;
      long long   fibN = 0;
      for(unsigned int i = 2; i <= n; ++ i)
       {
             fibN = fibNMinusOne + fibNMinusTwo;

             fibNMinusTwo = fibNMinusOne;
             fibNMinusOne = fibN;
       }

      return fibN;
}


这还不是最快的方法。下面介绍一种时间复杂度是O(logn)的方法。在介绍这种方法之前,先介绍一个数学公式:
{f(n), f(n-1), f(n-1), f(n-2)} ={1, 1, 1,0}n-1
(注:{f(n+1), f(n), f(n), f(n-1)}表示一个矩阵。在矩阵中第一行第一列是f(n+1),第一行第二列是f(n),第二行第一列是f(n),第二行第二列是f(n-1)。)
有了这个公式,要求得f(n),我们只需要求得矩阵{1, 1, 1,0}的n-1次方,因为矩阵{1, 1, 1,0}的n-1次方的结果的第一行第一列就是f(n)。这个数学公式用数学归纳法不难证明。感兴趣的朋友不妨自己证明一下。
现在的问题转换为求矩阵{1, 1, 1, 0}的乘方。如果简单第从0开始循环,n次方将需要n次运算,并不比前面的方法要快。但我们可以考虑乘方的如下性质:
         /   an/2*an/2                       n为偶数时
an=
         \   a(n-1)/2*a(n-1)/2             n为奇数时
要求得n次方,我们先求得n/2次方,再把n/2的结果平方一下。如果把求n次方的问题看成一个大问题,把求n/2看成一个较小的问题。这种把大问题分解成一个或多个小问题的思路我们称之为分治法。这样求n次方就只需要logn次运算了。
实现这种方式时,首先需要定义一个2×2的矩阵,并且定义好矩阵的乘法以及乘方运算。当这些运算定义好了之后,剩下的事情就变得非常简单。完整的实现代码如下所示。

C++代码 复制代码
  1. #include <cassert>   
  2. ///////////////////////////////////////////////////////////////////////   
  3. // A 2 by 2 matrix   
  4. ///////////////////////////////////////////////////////////////////////   
  5. struct Matrix2By2   
  6. {   
  7.        Matrix2By2   
  8.        (   
  9.             long long m00 = 0,    
  10.             long long m01 = 0,    
  11.             long long m10 = 0,    
  12.             long long m11 = 0   
  13.        )   
  14.        :m_00(m00), m_01(m01), m_10(m10), m_11(m11)    
  15.        {   
  16.        }   
  17.   
  18.       long long m_00;   
  19.       long long m_01;   
  20.       long long m_10;   
  21.       long long m_11;   
  22. };   
  23.   
  24. ///////////////////////////////////////////////////////////////////////   
  25. // Multiply two matrices   
  26. // Input: matrix1 - the first matrix   
  27. //         matrix2 - the second matrix   
  28. //Output: the production of two matrices   
  29. ///////////////////////////////////////////////////////////////////////   
  30. Matrix2By2 MatrixMultiply   
  31. (   
  32.       const Matrix2By2& matrix1,    
  33.       const Matrix2By2& matrix2   
  34. )   
  35. {   
  36.       return Matrix2By2(   
  37.              matrix1.m_00 * matrix2.m_00 + matrix1.m_01 * matrix2.m_10,   
  38.              matrix1.m_00 * matrix2.m_01 + matrix1.m_01 * matrix2.m_11,   
  39.              matrix1.m_10 * matrix2.m_00 + matrix1.m_11 * matrix2.m_10,   
  40.              matrix1.m_10 * matrix2.m_01 + matrix1.m_11 * matrix2.m_11);   
  41. }   
  42.   
  43. ///////////////////////////////////////////////////////////////////////   
  44. // The nth power of matrix    
  45. // 1   1   
  46. // 1   0   
  47. ///////////////////////////////////////////////////////////////////////   
  48. Matrix2By2 MatrixPower(unsigned int n)   
  49. {   
  50.        assert(n > 0);   
  51.   
  52.        Matrix2By2 matrix;   
  53.       if(n == 1)   
  54.        {   
  55.              matrix = Matrix2By2(1, 1, 1, 0);   
  56.        }   
  57.       else if(n % 2 == 0)   
  58.        {   
  59.              matrix = MatrixPower(n / 2);   
  60.              matrix = MatrixMultiply(matrix, matrix);   
  61.        }   
  62.       else if(n % 2 == 1)   
  63.        {   
  64.              matrix = MatrixPower((n - 1) / 2);   
  65.              matrix = MatrixMultiply(matrix, matrix);   
  66.              matrix = MatrixMultiply(matrix, Matrix2By2(1, 1, 1, 0));   
  67.        }   
  68.   
  69.       return matrix;   
  70. }   
  71.   
  72. ///////////////////////////////////////////////////////////////////////   
  73. // Calculate the nth item of Fibonacci Series using devide and conquer   
  74. ///////////////////////////////////////////////////////////////////////   
  75. long long Fibonacci_Solution3(unsigned int n)   
  76. {   
  77.       int result[2] = {0, 1};   
  78.       if(n < 2)   
  79.             return result[n];   
  80.   
  81.        Matrix2By2 PowerNMinus2 = MatrixPower(n - 1);   
  82.       return PowerNMinus2.m_00;   
  83. }  
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics