29 lines
813 B
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package dynamic_programming;
/**
* 题目: 70. 爬楼梯 (climbStairs)
* 描述:假设你正在爬楼梯。需要 n 阶你才能到达楼顶。
* 每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶呢?
示例 2
输入n = 2
输出2
解释:有两种方法可以爬到楼顶。
1. 1 阶 + 1 阶
2. 2 阶
* 链接https://leetcode.cn/problems/climbing-stairs/
*/
public class ClimbStairs {
public int climbStairs(int n) {
if(n <= 2) return n;
int a = 1, b = 2, sum = 0;
for(int i = 3; i <= n; i++){
sum = a + b; // f(i - 1) + f(i - 2)
a = b; // 记录f(i - 1)即下一轮的f(i - 2)
b = sum; // 记录f(i)即下一轮的f(i - 1)
}
return b;
}
}