标签:str end main 个人 system clu 问题 pac cci
1. 走台阶问题
有n级台阶,一个人每次上一级或者两级,问有多少种走完n级台阶的方法?
方法1:递归
#include <iostream>
using namespace std;
const int N = 100; //假设最多走100级台阶
int result[N]; //保存结果
int step(int n)
{
if(n > 2)
{
result[n] = step(n-1) + step(n-2);
}
return result[n];
}
int main()
{
int n;
cin >> n;
result[1] = 1;
result[2] = 2;
cout << step(n) << endl;
system("pause");
return 0;
}
方法2:自底向上
#include <iostream>
using namespace std;
const int N = 100; //假设最多走100级台阶
int result[N]; //保存结果
int step(int n)
{
for(int i = 3; i <= n; i++)
{
result[i] = result[i-1] + result[i-2];
}
return result[n];
}
int main()
{
int n;
cin >> n;
result[1] = 1;
result[2] = 2;
cout << step(n) << endl;
system("pause");
return 0;
}
2. 求斐波拉契数列Fibonacci
方法1:递归
#include <iostream>
using namespace std;
const int N = 101; //假设最多求到100
int result[N]; //保存结果
int fb(int n)
{
if(n >= 2)
{
result[n] = fb(n-1) + fb(n-2);
}
return result[n];
}
int main()
{
int n;
cin >> n;
result[0] = 0;
result[1] = 1;
cout << fb(n) << endl;
system("pause");
return 0;
}
方法2:自底向上
#include <iostream>
using namespace std;
const int N = 101; //假设最多求到100
int result[N]; //保存结果
int fb(int n)
{
for (int i = 2; i <= n; i++)
{
result[i] = result[i-1] + result[i-2];
}
return result[n];
}
int main()
{
int n;
cin >> n;
result[0] = 0;
result[1] = 1;
cout << fb(n) << endl;
system("pause");
return 0;
}
标签:str end main 个人 system clu 问题 pac cci
原文地址:https://www.cnblogs.com/mengjuanjuan/p/10165389.html