zoukankan      html  css  js  c++  java
  • Climbing Stairs leetcode java

    题目

    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?

    题解:

    这道题就是经典的讲解最简单的DP问题的问题。。

    假设梯子有n层,那么如何爬到第n层呢,因为每次只能怕1或2步,那么爬到第n层的方法要么是从第n-1层一步上来的,要不就是从n-2层2步上来的,所以递推公式非常容易的就得出了:

    dp[n] = dp[n-1] + dp[n-2]

    如果梯子有1层或者2层,dp[1] = 1, dp[2] = 2,如果梯子有0层,自然dp[0] = 0

    代码如下:

     1     public int climbStairs(int n) {
     2         if(n==0||n==1||n==2)
     3             return n;
     4         int [] dp = new int[n+1];
     5         dp[0]=0;
     6         dp[1]=1;
     7         dp[2]=2;
     8         
     9         for(int i = 3; i<n+1;i++){
    10             dp[i] = dp[i-1]+dp[i-2];
    11         }
    12         return dp[n];
    13     }

  • 相关阅读:
    c++ *.h和*.cpp在编译中的作用
    test
    DOM Tree
    SecureCRT
    趣味盒1
    数据结构笔试:前缀表达式|后缀表达式
    Shell 文件包含
    Shell 输入/输出重定向
    Shell 函数
    Shell 流程控制
  • 原文地址:https://www.cnblogs.com/springfor/p/3886576.html
Copyright © 2011-2022 走看看