#leetcode509
The 2021 year will pass,it's so fast!
I should prepare the final exam,but i have to finish my homework before this friday.
I don't care my homework,and i think the knowledge that i should acquire is important.
Today,i write a leetcode509,because this is a dynamic programming type,and this is a simple problem about fibonacci-number.
What is fibonacci-number?
Each number is the sum of the two preceding ones,starting from 0 and 1.
/*
fib(0) = 0,fib(1) = 1
input:n = 2
fib(2) = fib(1) + fib(0)
output: 1
input:n = 3
fib(3) = fib(2) + fib(1)
output: 2
input:n = 4
fib(4) = fib(3) + fib(2)
output: 3
*/
My first submitting is pass by using recursion,but executive time is bad.

When i read haoel solution,and i want to say that it's amazing.
I write this problem again,and executive time beat 100% clients!
class Solution {
public:
int fib(int n) {
if (n < 2)
return n;
int first = 0;
int second = 1;
for (n -= 1; n > 0; n--)
{
second += first;
first = second - first;//update the first value
}
return second;//return second value
}
};
When i read carl solution,and i think that his thinking is also same haoel one.
His executive time also beat %100 clients,but his memory consuming is better than haoel one.
class Solution {
public:
int fib(int n) {
if (n <= 1)
return n;
int dp[2];
dp[0] = 0;
dp[1] = 1;
for (int i = 2; i <= n; ++i)
{
int sum = dp[0] + dp[1];
dp[0] = dp[1];
dp[1] = sum;
}
return dp[1];
}
};
浙公网安备 33010602011771号