70 Climbing Stairs

来源:互联网 发布:网络作家排行榜2014 编辑:程序博客网 时间:2024/05/17 09:07

70 Climbing Stairs

链接:https://leetcode.com/problems/climbing-stairs/
问题描述:
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?

Hide Tags Dynamic Programming

假设n-1步时候上去的方法有k1种,n步时候上去的方法有k2种,那么只要能计算n+1上去的方法有多少中那么题目就可以解出来了。n+1步的时候最后一步爬1步那么剩下n步有k2种方法,最后一步跨2步,那么剩下n-1步有k1种方法,所以一共有k1+k2种方法。其实这就是个斐波那契数列。代码如下:

int climbStairs(int n) {    if (n <= 0)        return 0;           int a = 1,b = 1,c = 1,i=1;          for (; i < n; i++)           {            c=a+b;            a=b;            b=c;          }    return c;}
0 0