Question: There are n steps in the staircase. One, two, or three steps can be taken in one step. How many ways to go up the stairs?
Code:
#include<iostream>
using namespace std;
int cnt=0;//用于计数
void f(int n)//n表示还剩你个台阶需要走
{
if(n<0) return; //防止死循环
if(n==0)
{
cnt++;
return;
}
f(n-1); //走一步
f(n-2); //走两步
f(n-3); //走三步
}
int main()
{
int n;
cin>>n;
f(n);
cout<<cnt;
return 0;
}
Defects: When n is relatively large, it takes a lot of time and may even burst the stack. Analysis shows that there are a lot of repetitive sub-problems in the above recursion, and a lot of useless work is done. In order to solve the repetitive sub-problem, memory recursion can be used for optimization.
Code:
#include<iostream>
using namespace std;
int dp[1001];//假设楼梯的台阶数可以达到1000
int f(int n)//n表示还剩你个台阶需要走
{
if(dp[n]!=0) return dp[n];
int cnt=0;//用于计数
if(n<0) return 0; //防止死循环
if(n==0)
{
cnt++;
return cnt;
}
cnt+=f(n-1); //走一步
cnt+=f(n-2); //走两步
cnt+=f(n-3); //走三步
dp[n]=cnt;
return cnt;
}
int main()
{
int n;
cin>>n;
cout<<f(n);
return 0;
}