70. Climbing Stairs

来源:互联网 发布:博客如何发java代码 编辑:程序博客网 时间:2024/06/05 02:40

题目:

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.

思路:这道题目本质上是个动态规划的问题,虽然也可以用递归的方法做,但是时间复杂度太高,那么用动态规划就需要建立状态转移方程:X(i) = X(i-1) + X(i-2);   每次有两种选择,两种选择之后又是各有两种选择,如下图所示:


代码:

//简单的动态规划问题class Solution {public:    int climbStairs(int n) {        vector<int> res(n+1);        res[0] = 1;        res[1] = 1;        for(int i =2;i<=n;i++)        {            res[i] = res[i-1] + res[i-2];         }        return res[n];                    }};


原创粉丝点击