Leetcode: Climbing Stairs
2014-10-04 02:11
239 查看
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
;
}
}
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;
}
}
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
;
}
}
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;
}
}
相关文章推荐
- LeetCode - Climbing Stairs
- LeetCode 70 Climbing Stairs
- 【LeetCode】Climbing Stairs
- LeetCode算法问题16 —— Climbing Stairs
- LeetCode 70 Climbing Stairs(Python详解及实现)
- leetcode--Climbing Stairs
- leetcode-Java-70. Climbing Stairs
- LeetCode Online Judge 题目C# 练习 - Climbing Stairs
- LeetCode:Climbing Stairs
- LeetCode: Climbing Stairs
- 【LeetCode-动态规划】Climbing Stairs【较重要:含dp解题思路套路】
- [LeetCode] 70. Climbing Stairs
- LeetCode-70 climbing stairs(方法大总结)
- LeetCode - Fibonacci Sequence/Dynamic Programming - Climbing Stairs
- [LeetCode] Climbing Stairs [24]
- 【LeetCode】Climbing Stairs 解题报告
- [LeetCode][智力题]Climbing Stairs
- LeetCode题解:Climbing Stairs
- [Leetcode]-Climbing Stairs
- Climbing Stairs | leetcode 70 【Java解题报告】