42 lines
1.0 KiB
JavaScript
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.

/**
* @param {number} n
* @return {number}
*/
const climbStairs = function (n) {
};
/*
这个题目就是求斐波那契数列的现实抽象我们的最终目的是跳到第n个台阶而每一次要么跳一步要么跳两步
所以智能由n-1个台阶跳一步上来或者由n-2个台阶跳两步上来设dp[i]为跳转到这个台阶可能的方法,那么
dp[i] = dp[i-1] + dp[i-2]
*/
function f1(n) {
// 定义dp数组
const dp = Array(n + 1);
dp[1] = 1;
dp[2] = 2;
for (let i = 3; i <= n; i++) {
dp[i] = dp[i - 1] + dp[i - 2];
}
return dp[n];
}
/*
通过观察上面的代码可以知道dp[i]的结果只由它的前一个位置和前前个位置有关所以定义两个变量first和second来
保存这两个值
*/
function f2(n) {
if (n < 3) return n;
// 定义跳到前两个台阶可能的步数
let first = 1;
let second = 2;
let result = 1;
for (let i = 3; i <= n; i++) {
result = first + second;
first = second;
second = result;
}
return result;
}