Leetcode: Climbing Stairs
2014-01-07 20:52
423 查看
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?
算是简单的DP,如果想不到会感觉没思路。 最懒的方法是递归,不过时间过不了。
=====================第二次=====================
class Solution {
public:
int climbStairs(int n) {
if (n <= 2) {
return n;
}
int n1 = 1;
int n2 = 2;
int ways = 0;
for (int i = 3; i <= n; ++i) {
ways = n1 + n2;
n1 = n2;
n2 = ways;
}
return ways;
}
};
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
算是简单的DP,如果想不到会感觉没思路。 最懒的方法是递归,不过时间过不了。
class Solution { public: int climbStairs(int n) { if (n <= 2) { return n; } return (climbStairs(n-1) + climbStairs(n-2)); } };改成迭代就可以啦,利用前面计算过的结果。
class Solution { public: int climbStairs(int n) { if (n <= 2) { return n; } int sn, sn2 = 1, sn1 = 2; for (int i = 3; i <= n; ++i) { sn = sn2 + sn1; sn2 = sn1; sn1 = sn; } return sn; } };
=====================第二次=====================
class Solution {
public:
int climbStairs(int n) {
if (n <= 2) {
return n;
}
int n1 = 1;
int n2 = 2;
int ways = 0;
for (int i = 3; i <= n; ++i) {
ways = n1 + n2;
n1 = n2;
n2 = ways;
}
return ways;
}
};
相关文章推荐
- [Leetcode] Climbing Stairs
- leetcode-70 Climbing Stairs
- LeetCode70 Climbing Stairs 解题报告
- [LeetCode] [Climbing Stairs 2012-04-03]
- LeetCode:Climbing Stairs
- [leetcode] Climbing Stairs
- LeetCode70——Climbing Stairs
- LeetCode | Climbing Stairs
- 【leetcode】【70】Climbing Stairs
- LeetCode: Climbing Stairs
- Leetcode 70 Climbing Stairs 爬楼梯的方法(动态规划)
- LeetCode-Climbing Stairs
- Leetcode[72]-Climbing Stairs
- Leetcode-70 Climbing Stairs
- 【LeetCode】Climbing Stairs
- LeetCode 70 — Climbing Stairs(C++ Java Python)
- leetcode 刷题之路 92 Climbing Stairs
- LeetCode 70 Climbing Stairs(爬楼梯)(动态规划)(*)
- LeetCode_70---Climbing Stairs
- Climbing stairs--LeetCode