leetcode Climbing Stairs
2014-10-31 16:17
267 查看
最近开始刷leetcode的题,一直不太会做动态规划的题目,先找这方面题目做一做,用java。
目前动态规划的题目已经做完,再从易到难总结一下。
Climbing stairs 原题地址:
https://oj.leetcode.com/problems/climbing-stairs/
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?
n阶台阶,一次走一阶或两阶,有多少种不同的走法。
求走到第i阶台阶的走法,等于走到第i-2阶台阶的走法(再一次走两阶)加上走到第i-1阶台阶的走法(再走一阶)。
即f(i) = f(i-2) + f(i-1), i > 2, f(0) = 0, f(1) = 1, f(2) = 2
public class Solution {
public int climbStairs(int n) {
if (n == 0)
return 0;
if (n == 1)
return 1;
if (n == 2)
return 2;
int a = 1;
int b = 2;
for (int i = 2; i < n; i++) {
int temp = a;
a = b;
b = temp + b;
}
return b;
}
}
目前动态规划的题目已经做完,再从易到难总结一下。
Climbing stairs 原题地址:
https://oj.leetcode.com/problems/climbing-stairs/
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?
n阶台阶,一次走一阶或两阶,有多少种不同的走法。
求走到第i阶台阶的走法,等于走到第i-2阶台阶的走法(再一次走两阶)加上走到第i-1阶台阶的走法(再走一阶)。
即f(i) = f(i-2) + f(i-1), i > 2, f(0) = 0, f(1) = 1, f(2) = 2
public class Solution {
public int climbStairs(int n) {
if (n == 0)
return 0;
if (n == 1)
return 1;
if (n == 2)
return 2;
int a = 1;
int b = 2;
for (int i = 2; i < n; i++) {
int temp = a;
a = b;
b = temp + b;
}
return b;
}
}
相关文章推荐
- LeetCode - Climbing Stairs
- 【LeetCode】Climbing Stairs
- LeetCode 70. Climbing Stairs
- LeetCode Online Judge 题目C# 练习 - Climbing Stairs
- [LeetCode] Climbing Stairs, Solution
- [LeetCode] Climbing Stairs
- LeetCode(53) Climbing Stairs (剑指Offer->跳台阶、变态跳台阶)
- Climbing Stairs (leetcode)
- LeetCode - Fibonacci Sequence/Dynamic Programming - Climbing Stairs
- [LeetCode] Climbing Stairs [24]
- leetcode之 climbing stairs
- [leetcode]70. Climbing Stairs
- LeetCode 070 Climbing Stairs
- Leetcode | Climbing Stairs
- Leetcode Climbing Stairs
- LeetCode(70) Climbing Stairs
- LeetCode Climbing Stairs
- LeetCode题解:Climbing Stairs
- leetcode -- Climbing Stairs -- 简单重要
- [leetcode]41 Climbing Stairs