A description of the subject
We all know that Fibonacci number, and now asked to enter an integer n, you output the n-th Fibonacci number Fibonacci sequence of item (from 0, the first 0 is 0). n <= 39
Two Solution 1
1 analysis
Fibonacci sequence mathematical language description may be represented as f (n) = f (n-1) + f (n-2), (n> 1); f (n) = n, (n = 0, 1); apparent You can use a recursive thinking to solve this problem, recursive recursive formula and have a termination condition.
Complexity: time complexity of O (n ^ 2), the spatial complexity is O (1).
2 code implementation
1 class Solution { 2 public: 3 int Fibonacci(int n) { 4 if (n <= 0) 5 return 0; 6 if (n == 1) 7 return 1; 8 9 return Fibonacci(n - 1) + Fibonacci(n - 2); 10 } 11 };
Two Solution 2
1 analysis
Instead of using the iterative recursion, f (n) = f (n-1) + f (n-2), to calculate f (n) is calculated on the first f (n-1), f (n-2), the other way round sufficient to know f (1), f (2), then eventually know f (n).
Complexity: time complexity of O (n), the spatial complexity is O (1).
2 code implementation
. 1 class Solution { 2 public : . 3 int the Fibonacci ( int n-) { . 4 IF (n-<= 0 ) . 5 return 0 ; . 6 IF (n-== . 1 ) . 7 return . 1 ; . 8 . 9 int lastValue = . 1 ; // F ( n-1) value of 10 int lastLastValue = 0 ; // F (n-2-) values . 11 int RET; // return value 12 for ( int i = 2 ; i <= n; ++ i) 13 { 14 ret = load value + goods load value; 15 goods load value = load value; 16 load value = ret; 17 } 18 19 return ret; 20 } 21 };
This article summarizes the blog for their own learning, limited, if wrong, welcomed the discussion!