Leetcode Climbing Stairs
2015-09-23 13:38
501 查看
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?
假设梯子有n层,那么如何爬到第n层呢,因为每次只能怕1或2步,那么爬到第n层的方法要么是从第n-1层一步上来的,要不就是从n-2层2步上来的,所以递推公式非常容易的就得出了:
dp
= dp[n-1] + dp[n-2]
如果梯子有1层或者2层,dp[1] = 1, dp[2] = 2,如果梯子有0层,自然dp[0] = 0
Java code:
Reference:
1. http://www.cnblogs.com/springfor/p/3886576.html
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
= dp[n-1] + dp[n-2]
如果梯子有1层或者2层,dp[1] = 1, dp[2] = 2,如果梯子有0层,自然dp[0] = 0
Java code:
public int climbStairs(int n) { if(n == 0 || n==1 || n==2) { return n; } int[] dp = new int[n+1]; dp[0] = 0; dp[1] = 1; dp[2] = 2; for(int i = 3; i< n+1; i++){ dp[i] = dp[i-1] + dp[i-2]; } return dp ; }
Reference:
1. http://www.cnblogs.com/springfor/p/3886576.html
相关文章推荐
- 利用dbms_repair来标记和跳过坏块
- main函数的两个参数浅析
- Teorex Inpaint 6.0 简体中文最新破解版(自动去除图片上的水印)
- mybaits Could not find parameter map
- main函数中两个参数的用法
- VS修改项目名后出现的提示(warning MSB8028: The intermediate directory (Debug\) contains files shared from anoth)
- [CareerCup] 9.7 Paint Fill 填充
- Playfair密码加密
- 安卓工程修改包名后 Failed to find provider info for...问题
- 在C语言中执行shell命令 http://www.cnblogs.com/mydomain/archive/2013/04/20/3033076.html
- does not contain bitcode
- abap中使用Screen painter为普通屏幕创建单选按钮组radiobutton组的过程
- Lucene的IndexWriter初始化时的LockObtainFailedException的解决方法
- RAID磁盘阵列中LUN的理解
- 循环retain
- String中的contains()方法
- waitpid()
- 孤儿进程和僵尸进程 http://blog.csdn.net/liangkaiming/article/details/6230752
- linux管道学习 http://blog.csdn.net/qq1355541448/article/details/8460835
- (转)Linux下管道的原理 http://blog.csdn.net/guang11cheng/article/details/17144907