Original question:
There are three types of stairs in the 100 class, one step at a time, two steps at a time, and three steps at a time. How many steps are there after 100 steps using algorithms?
Answer:
F (n) = f (n-1) + f (n-2) + f (n-3)
There are two key points: 1. The result is greater than int32 and requires high precision. 2. Direct recursion involves a large number of repeated operations, and the results of each step must be cached.
# Include "stdio. h"
Void addCache (char count [], char d []);
Void reverse (int index );
Void lastMove (int stepOver );
Char result [100];
Char cache [101] [100];
Void main ()
{
For (int I = 0; I <101; I ++)
{
Cache [I] [0] = 0;
For (int j = 1; j <100; j ++)
{
Cache [I] [j] = 0;
}
}
Cache [0] [0] = '0 ';
Cache [1] [0] = '1 ';
Cache [2] [0] = '2 ';
Cache [3] [0] = '4 ';
Int floor = 100;
LastMove (floor );
Reverse (floor );
Printf ("total: % s", result );
}
Void lastMove (int stepOver)
{
If (stepOver> 3)
{
For (int I = 1; I <= 3; I ++)
{
Int index = stepOver-I;
If (cache [index] [0] = 0) // not cached
{
LastMove (index );
}
AddCache (cache [stepOver], cache [index]);
}
}
Else
{
Printf ("error \ n ");
}
}
Void addCache (char count [], char d [])
{
Int j = 0;
While (d [j]! = 0)
{
Int in = d [j]-'0 ';
For (int I = j; I <100; I ++)
{
If (in = 0)
{
Break;
}
If (count [I] = '\ 0 ')
{
Count [I] = '0 ';
}
Int curNum = count [I]-'0' + in;
If (curNum> 9)
{
In = curNum/10;
CurNum-= in * 10;
}
Else
{
In = 0;
}
Count [I] = curNum + '0 ';
}
J ++;
}
}
Void reverse (int index)
{
Int length = 0;
For (int I = 0; I <100; I ++)
{
If (cache [index] [I] = 0)
{
Length = I;
Break;
}
}
For (I = 0; I <length; I ++)
{
Result [length-1-I] = cache [index] [I];
}
Result [length] = 0;
}