Lizou punch card 2021.1.4 Fibonacci sequence problem

Topic:
Fibonacci number, usually expressed by F(n), the sequence formed is called Fibonacci sequence. The number sequence starts with 0 and 1, and each number after it is the sum of the previous two numbers. That is:

F(0) = 0, F(1) = 1
F(n) = F(n-1) + F(n-2), where n> 1
gives you n, please calculate F(n).

Example 1:

Input: 2
Output: 1
Explanation: F(2) = F(1) + F(0) = 1 + 0 = 1
Example 2:

Input: 3
Output: 2
Explanation: F(3) = F(2) + F(1) = 1 + 1 = 2
Example 3:

Input: 4
Output: 3
Explanation: F(4) = F(3) + F(2) = 2 + 1 = 3

Idea:
Two words, recursion.

代码:
class Solution {
public:
int fib(int n) {
if (n= =0)
return 0;
if (n= =1)
return 1;
else
return fib(n-1)+fib(n-2);

}

};

Guess you like

Origin blog.csdn.net/weixin_45780132/article/details/112171952