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

2014-03-20 02:55

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

解法:斐波那契数列。

代码:

 1 // 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?
 2 #include <cstdio>
 3 #include <vector>
 4 using namespace std;
 5 
 6 int main()
 7 {
 8     int n;
 9     int i;
10     vector<int> v;
11     
12     v.push_back(1);
13     n = 1;
14     while (true) {
15         i = v[n - 1];
16         if (n >= 2) {
17             i += v[n - 2];
18         }
19         if (n >= 3) {
20             i += v[n - 3];
21         }
22         if (i >= 1000000000) {
23             break;
24         } else {
25             v.push_back(i);
26         }
27         ++n;
28     }
29     printf("n = %d\n", (int)v.size());
30     
31     while (scanf("%d", &n) == 1 && n > 0 && n < (int)v.size()) {
32         printf("%d\n", v[n]);
33     }
34     v.clear();
35     
36     return 0;
37 }

 

转载于:https://www.cnblogs.com/zhuli19901106/p/3612784.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值