私は LeetCode #70 でこの問題の解決策を持っています。
サンクを利用するトランポリンを追加し、メモ化を追加しました。これをスピードアップして、コードが以下にあるこの問題の時間要件を実際に渡すために追加できるものは他にありません。事前に感謝します。
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];
};