【发布时间】:2020-08-19 15:36:06
【问题描述】:
我在 LeetCode #70 爬楼梯上有这个问题的解决方案,我的解决方案没有通过,因为它很慢......
我已经添加了一个使用 thunk 的蹦床,并且我已经添加了记忆,我还可以添加什么来加速它以实际通过我的代码在下面的这个问题的时间要求,并提前致谢。
关于 LeetCode 的描述:
你正在爬楼梯。到达顶部需要 n 步。
每次您可以爬 1 或 2 级台阶。您可以通过多少种不同的方式登顶?
注意:给定 n 将是一个正整数。
Example 1:
Input: 2
Output: 2
Explanation: There are two ways to climb to the top.
1. 1 step + 1 step
2. 2 steps
Example 2:
Input: 3
Output: 3
Explanation: There are three ways to climb to the top.
1. 1 step + 1 step + 1 step
2. 1 step + 2 steps
3. 2 steps + 1 step
LeetCode 上的问题链接:https://leetcode.com/problems/climbing-stairs/
let cache = {};
const sumStairSteps = arr => arr.reduce((acc, cur) => acc + cur, 0);
const thunk = (fn, ...args) => {
return () => fn(...args);
}
const climbStairsHelper2 = fn => {
let thunk = fn();
while (typeof thunk === "function") {
thunk = thunk();
}
return thunk;
};
const climbStairs2 = (newStairSequence, ladderCount) => {
const sum = sumStairSteps(newStairSequence);
if (sum === ladderCount) { cache[ladderCount] = cache[ladderCount] + 1; }
if (1 + sum <= ladderCount) {
climbStairsHelper2(thunk(climbStairs2, [ ...newStairSequence, 1 ], ladderCount));
}
if (2 + sum <= ladderCount) {
climbStairsHelper2(thunk(climbStairs2, [ ...newStairSequence, 2 ], ladderCount));
}
};
const climbStairs = n => {
if (n in cache) return cache[n];
cache[n] = 0;
climbStairs2([], n);
console.log(cache[n]);
return cache[n];
};
【问题讨论】:
-
你到底想在这里做什么?
-
我正在尝试提高解决方案的速度。
-
不,我的意思是,您能解释一下您发布的代码的用途吗?
-
我正在使用带有递归的记忆,我也在使用带有 thunk 的蹦床以避免堆栈溢出异常。
-
但是你真正想要解决的问题是什么?
标签: javascript recursion optimization dynamic-programming trampolines