/**
* 上台阶问题
* 一次可以上一阶台阶,也可以上二阶台阶,请上N阶台阶有几种方法?
*/
// 递归
function jump(n) {
if (n <= 0) return 0;
if (n == 1) return 1;
if (n == 2) return 2;
return jump(n - 1) + jump(n - 2)
}
// 循环上 N 阶 就是前两次相加
function jump2(n) {
let target = 0;
let n1 = 1;
let n2 = 2;
if (n <= 0) return 0;
if (n == 1) return 1;
if (n == 2) return 2;
for (let i = 3; i <= n; i++) {
target = n1 + n2;
n1 = n2;
n2 = target;
}
return target;
}
const res1 = jump(10);
const res2 = jump2(10);
console.log('res1: ', res1);
console.log('res2: ', res2);