第十六周LeetCode
来源:互联网 发布:福州广电网络 编辑:程序博客网 时间:2024/05/22 17:34
题目
Climbing Stairs
难度 easy
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.
Example 1:
Input: 2
Output: 2
Explanation: There are two ways to climb to the top.
- 1 step + 1 step
- 2 steps
Example 2:
Input: 3
Output: 3
Explanation: There are three ways to climb to the top.
- 1 step + 1 step + 1 step
- 1 step + 2 steps
- 2 steps + 1 step
实现思路
可以用动态规划实现。因为每次只能走一步或两步,设dp[i]为走第i阶楼梯时的可选走法数,则dp[i]取决于dp[i-1]和dp[i-2],即如果走一步到达dp[i]就有dp[i-1]种走法,走两步到达dp[i]就有dp[i-2]种走法,因此dp[i]=dp[i-1]+dp[i-2].由该状态转移方程可知需要先初始化dp[0]和dp[1]。
实现代码
int climbStairs(int n) { //one_step表示前一步的可选走法数量,two_step表示前两步的可选走法数量 int one_step = 1, two_step = 1; int steps = 0; if (n == 0 || n == 1) return 1; for (int i = 2; i <= n; i++) { steps = one_step+two_step; two_step = one_step; one_step = steps; } return steps; }
阅读全文
0 0
- leetcode-第十六周
- 第十六周leetcode
- 第十六周LeetCode
- 第十六周LeetCode
- 第十六周LeetCode
- LeetCode题解 第十六周
- leetcode 第十六周解题报告
- 第十六周LeetCode算法题两道
- 第十六周:[leetCode] 79. Word Search
- leetcode【第十六周】左叶子节点求和
- leetcode第十六周解题总结--图
- 第十六周
- 第十六周
- 第十六周
- 第十六周
- 第十六周
- 第十六周
- 第十六周
- MAC
- SbulimeText3密匙
- 用shell脚本写的一个简单的计算器
- Presto-[6]-JDBC Driver 简介与Demo测试
- 每日总结
- 第十六周LeetCode
- (二)tomcat服务器配置虚拟主机
- Tip:MySQL数据库中关于数据表ID重置
- Linux 下分析Java程序CPU使用高的问题
- SCRAPY_part2_基础TIPS
- 阻塞queue系列之ArrayBlockingQueue
- Win7(64)+eclipse(64)+tomcat7(64)+jdk7(64)开发环境配置
- 171220
- 【BZOJ1010】玩具装箱