70. 爬楼梯
假设你正在爬楼梯。需要 n 阶你才能到达楼顶。
每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶呢?
注意:给定 n 是一个正整数。
示例1:
输入: 2
输出: 2
解释: 有两种方法可以爬到楼顶。
1. 1 阶 + 1 阶
2. 2 阶
示例2:
输入: 3
输出: 3
解释: 有三种方法可以爬到楼顶。
1. 1 阶 + 1 阶 + 1 阶
2. 1 阶 + 2 阶
3. 2 阶 + 1 阶
解法
思路:
- 这是一道简单的题 对吧 但是 遇到这种题目 很多时候我们都会很懵逼 找不到思路
- 懵逼的时候 暴力???(暴力解决是一种非常好的办法,只是性能差一点而已) || 基本情况???(这个就要看实际情况来定,我们找到每个题目的基本情况)
- 计算机人人类发明的一种工具,就目前来说,计算机是没人类聪明的,只是计算速度快而已.
- 对此,我们就应该找到最近的 重复的子问题….
- 搞来搞去 我们能用的还是 if else for while recursion
- 1: 1
- 2: 2
- 3: f(1) + f(2)
- 4: f(3) + f(2)
- 数学归纳出
- f(n) = f(n-1) + f(n-2) : Fibonacci
直接递归,但是运行超时
var climbStairs = function (n) {
if (n <= 2) return n;
return climbStairs(n - 1) + climbStairs(n - 2);
};
在这里我们用时间换取空间
var climbStairs = function(n) {
if(n <= 2) return n
let f1 = 1, f2 = 2, f3 = 3
for(let i = 3; i < n + 1; i++) {
f3 = f1 + f2
f1 = f2
f2 = f3
}
return f3
};