您的位置:首页 > 其它

《Cracking the Coding Interview》——第9章:递归和动态规划——题目1

2014-03-20 02:55 423 查看
2014-03-20 02:55

题目:小朋友跳台阶,每次跳1层或2层,那么跳N层总共有多少种跳法。

解法:斐波那契数列。

代码:

// 9.1 A child can run up the stair with n staircases. Every time he can hop up by 1, 2 or 3 steps. How many possible way to do this are there?
#include <cstdio>
#include <vector>
using namespace std;

int main()
{
int n;
int i;
vector<int> v;

v.push_back(1);
n = 1;
while (true) {
i = v[n - 1];
if (n >= 2) {
i += v[n - 2];
}
if (n >= 3) {
i += v[n - 3];
}
if (i >= 1000000000) {
break;
} else {
v.push_back(i);
}
++n;
}
printf("n = %d\n", (int)v.size());

while (scanf("%d", &n) == 1 && n > 0 && n < (int)v.size()) {
printf("%d\n", v
);
}
v.clear();

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐