366. Fibonacci【Naive】

Find the Nth number in Fibonacci sequence.

A Fibonacci sequence is defined as follow:

  • The first two numbers are 0 and 1.
  • The i th number is the sum of i-1 th number and i-2 th number.

The first ten numbers in Fibonacci sequence is:

0, 1, 1, 2, 3, 5, 8, 13, 21, 34 ...

Notice

The Nth fibonacci number won't exceed the max value of signed 32-bit integer in the test cases.

 
Example

Given 1, return 0

Given 2, return 1

Given 10, return 34

题意

查找斐波纳契数列中第 N 个数。

所谓的斐波纳契数列是指:

  • 前2个数是 0 和 1 。
  • 第 i 个数是第 i-1 个数和第i-2 个数的和。

解法一:

 class Solution {
public:
/*
* @param n: an integer
* @return: an ineger f(n)
*/
int fibonacci(int n) {
int a, b;
a = ;
b = ; for (int i = ; i < n; i++) {
int c = a + b;
a = b;
b = c;
}
return a;
}
};

解法二:

 class Solution {
public:
/*
* @param n: an integer
* @return: an ineger f(n)
*/
int fibonacci(int n) {
if (n == ) {
return ;
} else if (n == ) {
return ;
} return fibonacci(n - ) + fibonacci(n - ); }
};

递归会超时

 

上一篇:如何去掉delphi2010的欢迎界面(welcome page)


下一篇:产品需求文档(PRD)的写作方法之笔记一