zoukankan      html  css  js  c++  java
  • 2016.6.21——Climbing Stairs

    Climbing Stairs

    本题收获:

    1.斐波那契函数f(n) = f(n-1) + f(n -2)

      题目: 

      You are climbing a stair case. It takes n steps to reach to the top.

      Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?

      有n阶台阶,每次可以走2步或者1步,问有多少种方法到达顶端

      思路:

        leetcode:是个斐波那契函数的迭代

          对于第n阶来说,有两种方法,从n-1 走 1阶 到n,  从n-2走2阶到n(刚开始想从n-2处到n 可以走1次2步  和  2次 1步,但是走1次一步不就成了n-1到n了, 重复)

      代码:

     1 class MyClass
     2 {
     3 public:
     4     int clambingStairs(int n)
     5     {
     6         if (n == 0) return 0;
     7         if (n == 1) return 1;
     8         if (n == 2) return 2;
     9 
    10         int f2 = 1, f1 = 2, f = 0;        
    11         for (int i = 2; i < n; i++)
    12         {
    13             f = f1 + f2;                //f2可以看做f(n-2)
    14             f2 = f1;                    //f1看做f(n-1)
    15             f1 = f;                        //f看做f(n)
    16         }
    17         return f;
    18     }
    19 };

      我的测试代码:

     1 // Climbing Stairs.cpp : 定义控制台应用程序的入口点。
     2 //
     3 
     4 #include "stdafx.h"
     5 #include "iostream"
     6 using namespace std;
     7 
     8 class MyClass
     9 {
    10 public:
    11     int clambingStairs(int n)
    12     {
    13         if (n == 0) return 0;
    14         if (n == 1) return 1;
    15         if (n == 2) return 2;
    16 
    17         int f2 = 1, f1 = 2, f = 0;        
    18         for (int i = 2; i < n; i++)
    19         {
    20             f = f1 + f2;                //f2可以看做f(n-2)
    21             f2 = f1;                    //f1看做f(n-1)
    22             f1 = f;                        //f看做f(n)
    23         }
    24         return f;
    25     }
    26 };
    27 
    28 
    29 
    30 
    31 int _tmain(int argc, _TCHAR* argv[])
    32 {
    33     int n = 0;
    34     cin >> n;
    35     MyClass solution;
    36     int m = 0;
    37     m = solution.clambingStairs(n);
    38     cout << m << endl;
    39     system("pause");
    40     return 0;
    41 }
  • 相关阅读:
    POJ 3904 Sky Code [数学]
    UVA 11542 Square [XOR方程组]
    CSS+DIV 设置圆角边框加阴影效果
    取消谷歌CHROME文本框(域)外边框高亮和缩放功能的办法
    IE和火狐CSS透明层兼容写法
    Ubuntu 12.04 amd64 搭建Apache+PHP+Mysql环境
    CSS样式表的优先级别
    css设置透明层
    卸载gnome的命令为
    ubuntu12.04 启动n卡独显方法
  • 原文地址:https://www.cnblogs.com/zhuzhu2016/p/5603632.html
Copyright © 2011-2022 走看看