I want to illustrate how efficient dynamic programming is compared to recursion
A man is running up a staircase with n steps, and can go either 1 steps or 2 steps at a time. Now write a program to count how many possible ways the child can run the stairs.
Implemented a program using recursion
int Stairs(int n)
{
int count = 0;
if (n <= 1)
return 1;
return Stairs(n-1) + Stairs(n-2);
}
Implemented a program using Dynamic Programming
int StairsDP(int n)
{vector<int> count;
count.reserve(n);
int temp;
count.push_back(1);
count.push_back(1);
if (n <= 1)
return 1;
for (int index=2; index <= n; index++)
{
temp = count[index-1] + count[index-2];
count.push_back(temp);
}
return count[n];
}
Collected some timing on my personal computer
Recursion
10 0.214255 ms.
20 0.240877 ms.
30 6.01229 ms.
Dynamic Programming
10 0.0971846 ms.
20 0.0538845 ms.
30 0.0535638 ms.
You see substantial improvements in efficiency for small values of n
No comments:
Post a Comment