Would you like to clone this notebook?

When you clone a notebook you are able to make changes without affecting the original notebook.

Cancel

solution-tencent-can-run

node v14.20.1
version: master
endpointsharetweet
const memo = new Map(); memo.set(1, 1); memo.set(0, 0); function f(n) { if (memo.has(n)) { return memo.get(n); } let a1 = Infinity; let a2 = Infinity; let a3 = Infinity; if (n % 2 === 0) { // 右移1等于除2 a2 = f(n >> 1); } if (n % 3 === 0) { a3 = f(n / 3); } // 剪枝,如果一直算这个会爆栈 if (a2 === Infinity || a3 === Infinity) { a1 = f(n - 1); } let ret = Math.min(a1, a2, a3) + 1; // 记忆化 memo.set(n, ret); return ret; } for (let i = 0; i < 20; ++i) { console.log(`${i}: ${f(i)}`); }
Loading…

no comments

    sign in to comment