mirror of
https://hub.njuu.cf/TheAlgorithms/C-Plus-Plus.git
synced 2023-10-11 13:05:55 +08:00
Merge pull request #289 from shoaibrayeen/patch-1
Space Optimization for the code - Constant Space
This commit is contained in:
commit
641514acb4
@ -2,14 +2,16 @@
|
|||||||
using namespace std;
|
using namespace std;
|
||||||
int fib(int n)
|
int fib(int n)
|
||||||
{
|
{
|
||||||
int res[n + 1];
|
int res[3];
|
||||||
res[0] = 0;
|
res[0] = 0;
|
||||||
res[1] = 1;
|
res[1] = 1;
|
||||||
for (int i = 2; i <= n; i++)
|
for (int i = 2; i <= n; i++)
|
||||||
{
|
{
|
||||||
res[i] = res[i - 1] + res[i - 2];
|
res[2] = res[1] + res[0];
|
||||||
|
res[0] = res[1];
|
||||||
|
res[1] = res[2];
|
||||||
}
|
}
|
||||||
return res[n];
|
return res[1];
|
||||||
}
|
}
|
||||||
int main(int argc, char const *argv[])
|
int main(int argc, char const *argv[])
|
||||||
{
|
{
|
||||||
@ -19,4 +21,4 @@ int main(int argc, char const *argv[])
|
|||||||
cout << "Fibonacci number is ";
|
cout << "Fibonacci number is ";
|
||||||
cout << fib(n) << endl;
|
cout << fib(n) << endl;
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user