solution2-tencent

node v10.24.1
version: master
endpointsharetweet
const n = +readline(); let input = []; for (let i = 0; i < n; ++i) { input.push(+readline()); } 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 (const n of input) { print(f(n)); }
Loading…

no comments

    sign in to comment