LeetCode -- 70. Climbing Stairs

来源:互联网 发布:换头型软件 编辑:程序博客网 时间:2024/06/05 05:13

题目:

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?

Note: Given n will be a positive integer.


思路:
这道题很简单,最简单的动态规划,也是一个斐波那契数列。
定义d[i]为i阶楼梯的方法数,那么到达第i阶楼梯只有两种方法,从i-1阶楼梯上一个台阶,从i-2个台阶上两个楼梯。
初始状态:

d[0]=d[1]=1;

状态转移方程:
d[i]=d[i1]+d[i2],i>=2;


C++代码:

class Solution {public:    int climbStairs(int n) {        int d[100];        d[0]=1, d[1]=1;        for(int i=2;i<=n;i++)        {            d[i] = d[i-1]+d[i-2];        }        return d[n];    }};
原创粉丝点击