leetcode #70 in cpp

原创 2016年05月31日 09:14:19

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?


Solution:

We use DP. see comments.

Code:

class Solution {
public:

    int climbStairs(int n) {
       vector<int> dp(n+1,0);//dp[i] = distinct ways from i to n
       if(n-1 >= 0) dp[n-1] = 1;//position with 1 step from destination. only 1 way to reach the destination
       if(n-2 >= 0) dp[n-2] = 2;//position with 2 steps from destination. only 2 way to reach the destination;
       for(int i = n-3; i >=0 ; i --){
           dp[i] = dp[i+2]+dp[i+1];//distinct ways from position i to n: 1. we take one step to i+1; 2. we take 2 steps to i+2
       }                            //thus distinct ways from position i to n is the sum of the ones at i+1 and i+2
       return dp[0];
       
    }
};

爬楼梯(leetcode-70)

需要爬一个n阶楼梯来到达楼梯顶部,每次可以爬1阶也可以爬2阶。求共有多少种爬法? 递归:到达n的“前一步”走法可以是:从n-1处爬1阶楼梯,或者从n-2处爬2阶楼梯。那么递归表达式即写成return ...
  • u013632190
  • u013632190
  • 2016年07月27日 23:42
  • 690

leetcode 70 Climbing Stairs

Climbing Stairs                       You are climbing a stair case. It takes n steps to reach t...
  • wangyaninglm
  • wangyaninglm
  • 2015年04月29日 17:46
  • 2817

leetcode70题 题解 翻译 C语言版 Python版

70. Climbing Stairs You are climbing a stair case. It takes n steps to reach to the top. Eac...
  • yingzinanfei
  • yingzinanfei
  • 2016年02月13日 17:21
  • 1053

Weekly Contest 70 leetcode 779. K-th Symbol in Grammar

On the first row, we write a 0. Now in every subsequent row, we look at the previous row and repla...
  • huanghanqian
  • huanghanqian
  • 2018年02月04日 18:40
  • 171

LeetCode-70 Climbing Stairs(斐波那契数列)

LeetCode-70 Climbing Stairs(斐波那契数列) You are climbing a stair case. It takes n steps to reach to the...
  • u011035622
  • u011035622
  • 2015年05月02日 11:35
  • 598

LeetCode(70) Climbing Stairs

题目You are climbing a stair case. It takes n steps to reach to the top.Each time you can either climb...
  • fly_yr
  • fly_yr
  • 2015年08月19日 21:54
  • 2787

leetcode之70. Climbing Stairs(C++解法 动态规划思想)

原题: You are climbing a stair case. It takes n steps to reach to the top.Each time you can either cl...
  • haimianxiaodao
  • haimianxiaodao
  • 2016年09月21日 15:19
  • 354

LeetCode 70 Climbing Stairs(Python详解及实现)

【题目】 You are climbing a stair case. It takes nsteps to reach to the top.   Each time you can eith...
  • yangjingjing9
  • yangjingjing9
  • 2017年08月05日 12:56
  • 273

LeetCode 70

Climbing Stairs 这个题的意思是爬阶梯,一次可以爬两个台阶或者一个台阶,问有多少种方法爬到顶。这确实是个easy的问题,见过这种问题的人可能很快就能写出代码,因为这个问题就是斐波拉写数...
  • zr1076311296
  • zr1076311296
  • 2016年07月06日 23:44
  • 824

leetcode 70

You are climbing a stair case. It takes n steps to reach to the top. Each time you can either cli...
  • weixin_35656147
  • weixin_35656147
  • 2017年04月03日 12:31
  • 55
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:leetcode #70 in cpp
举报原因:
原因补充:

(最多只允许输入30个字)