题解 | #称砝码#
称砝码
https://www.nowcoder.com/practice/f9a4c19050fc477e9e27eb75f3bfd49c
动态规划解法 完整代码如下:
const rl = require("readline").createInterface({ input: process.stdin }); var iter = rl[Symbol.asyncIterator](); const readline = async () => (await iter.next()).value; let lines = []; void async function () { // Write your code here while(line = await readline()){ lines.push(line); let n = parseInt(lines[0]); if (lines.length == 3) { let dp = Array(n + 1).fill([0]); let arr1 = lines[1].split(' ').map(Number); let arr2 = lines[2].split(' ').map(Number); for (let i = 1; i <= n; i++) { let index = 1; let m = arr1[i-1]; let k = arr2[i-1]; dp[i] = dp[i].concat(Array(k).fill(0).map(x => m*(index++))); }//以上的dp是将每个重量砝码单独的组合形式列了出来 for (let i = 1; i <= n; i++) { dp[i] = expand(dp[i], dp[i-1]);//利用双重循环 对dp[i]重新赋值 更新之后的值为原dp[i]和dp[i-1]分别交叉相加之后的新数组,再利用set去重,则得到最终的dp[i] } console.log(dp[n].length) } } }() function expand(arr1, arr2) { let res = []; for (let i = 0; i < arr1.length; i++) { for (let j = 0; j < arr2.length; j++) { res.push(arr1[i] + arr2[j]) } } res = [...new Set(res)]; return res; }