Leetcode: Climbing Stairs
来源:互联网 发布:淘宝买家评价语大全 编辑:程序博客网 时间:2024/05/06 00:40
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?
The following solution uses the equation step[ i ] = step[i - 1] + step[i - 2], but require O(n) space.
public class Solution { public int climbStairs(int n) { int[] step = new int[n + 1]; step[0] = 1; step[1] = 1; for (int i = 2; i <= n; i++) { step[i] = step[i - 1] + step[i - 2]; } return step[n]; }}
Since we don't need the results of previous steps, there's no need to use an array. Only need to store the last result. So revise the above code to the following:
public class Solution { public int climbStairs(int n) { int last = 1; int lastlast = 1; int res = 1; for (int i = 2; i <= n; i++) { res = last + lastlast; lastlast = last; last = res; } return res; }}
0 0
- LeetCode: Climbing Stairs
- LeetCode: Climbing Stairs
- [LeetCode]Climbing Stairs
- LeetCode Climbing Stairs
- [Leetcode] Climbing Stairs
- Leetcode: Climbing stairs
- LeetCode Climbing Stairs
- [LeetCode] Climbing Stairs
- leetcode 107: Climbing Stairs
- [LeetCode] Climbing Stairs
- [LeetCode]Climbing Stairs
- [leetcode]Climbing Stairs
- LeetCode-Climbing Stairs
- [leetcode] Climbing Stairs
- LeetCode - Climbing Stairs
- LeetCode:Climbing Stairs
- Leetcode Climbing Stairs
- LeetCode | Climbing Stairs
- Android Fragments
- UITextField部分用法
- 【Java.Web】JSP —— 语法基础 —— JSP指令Directives(page include taglib)
- html 文字标签
- 几种归一化方法(Normalization Method)python实现
- Leetcode: Climbing Stairs
- 学习网站累积(不断更新)
- python控制语句
- 西工大10级保研机试 柱状图
- [Python学习] 简单网络爬虫抓取博客文章及思想介绍
- 输出1,2,3,……,n
- 二分查找代码练习
- 关于伪代码
- Hibernate Annotation使用