Climbing Stairs leetcode java

 2023-09-05 阅读 32 评论 0

摘要:题目: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层,

题目

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     }

 

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/1/1727.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息