509. Fibonacci Number
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
提示:
0 <= n <= 30
Today's Likou Daily Question is relatively simple, entry-level dynamic programming, so I wrote it in three languages.
Routine dynamic planning;
int fib(int n){
if(n==0)
return 0;
if(n==1)
return 1;
int dp[n+1];
dp[0]=0;
dp[1]=1;
for(int i=2;i<n+1;i++)
{
dp[i]=dp[i-1]+dp[i-2];
}
return dp[n];
}
Scrolling array optimization:
int fib(int n){
if(n==0)
return 0;
if(n==1)
return 1;
int first,second,temp;
first=0;
second=1;
for(int i=2;i<n+1;i++)
{
temp=second;
second=second+first;
first=temp;
}
return second;
}
Python:
class Solution:
def fib(self, n: int) -> int:
if n==0:
return 0
if n==1:
return 1
first=0
second=1
temp=0
for i in range(2,n+1):
temp=second
second=second+first
first=temp
return second
C++:
class Solution {
public:
int fib(int n) {
if(n==0)
return 0;
if(n==1)
return 1;
int first,second,temp;
first=0;
second=1;
for(int i=2;i<n+1;i++)
{
temp=second;
second=second+first;
first=temp;
}
return second;
}
};