LeetCode - Climbing Stairs
2014-01-15 10:41
204 查看
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?
http://oj.leetcode.com/problems/climbing-stairs/
Solution:
Simple dp. We know that if there is one stair, we have one way, if there are two stairs, we have two ways.
So assume we have step
ways for n stairs, and for n+1 stairs, step[n+1] = step
+ step[n-1]. We can use step
+ 1 or step[n-1] + 2.
Does this formula seem similar? Sure it is Fibonacci number!!!
So I just provide the iterative way for this problem.
https://github.com/starcroce/leetcode/blob/master/climbing_stairs.cpp
//8 ms for 45 test cases
class Solution {
public:
int climbStairs(int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int a = 1, b = 2;
if(n == 1) {
return a;
}
if(n == 2) {
return b;
}
int c;
for(int i = 3; i <= n; i++) {
c = a + b;
a = b;
b = c;
}
return c;
}
};
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
http://oj.leetcode.com/problems/climbing-stairs/
Solution:
Simple dp. We know that if there is one stair, we have one way, if there are two stairs, we have two ways.
So assume we have step
ways for n stairs, and for n+1 stairs, step[n+1] = step
+ step[n-1]. We can use step
+ 1 or step[n-1] + 2.
Does this formula seem similar? Sure it is Fibonacci number!!!
So I just provide the iterative way for this problem.
https://github.com/starcroce/leetcode/blob/master/climbing_stairs.cpp
//8 ms for 45 test cases
class Solution {
public:
int climbStairs(int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int a = 1, b = 2;
if(n == 1) {
return a;
}
if(n == 2) {
return b;
}
int c;
for(int i = 3; i <= n; i++) {
c = a + b;
a = b;
b = c;
}
return c;
}
};
相关文章推荐
- LeetCode 70:Climbing Stairs
- (java)leetcode-70:Climbing Stairs
- [LeetCode]--Climbing Stairs
- leetcode 虐我篇之(二十一)Climbing Stairs
- LeetCode Climbing Stairs
- 【题解】【DP】【Leetcode】Climbing Stairs
- [Leetcode 70, easy] Climbing Stairs
- LeetCode:Climbing Stairs
- [LeetCode] Climbing Stairs
- 【LeetCode】遇到一个很有趣的问题:Climbing Stairs
- LeetCode 070 Climbing stairs
- leetcode(20).70. Climbing Stairs
- LeetCode: 013-Climbing Stairs
- [LeetCode] Climbing Stairs (Sequence DP)
- LeetCode-Climbing Stairs
- Leetcode: Climbing stairs
- 【leetcode】Climbing Stairs
- 【Leetcode】【python】Climbing Stairs
- leetcode:Climbing Stairs
- leetcode 107: Climbing Stairs