尝试将一些以前计算的值存储到哈希图中。我已经在另一个程序中完成了此操作,但它可以正常工作,但是由于某种原因,我现在遇到了错误。
我要解决的问题: 给定一些正整数n,编写一种方法以返回最少的完美平方和,总和为n。
一般来说,我是javascript和动态语言的新手,所以我可以尝试的东西不多。
此代码中的哈希映射正常工作:
function numSignWays(arr, sum) {
return findWays(arr, sum, 0, 0, {})
}
function findWays(arr, sum, p, currSum, hash) {
const key = p - currSum;
if(hash.hasOwnProperty(key))
return hash[key];
if (p < arr.length) {
const positive = findWays(arr, sum, p + 1, currSum + arr[p], hash);
const negative = findWays(arr, sum, p + 1, currSum - arr[p], hash);
const totalMatches = positive + negative;
hash[key] = totalMatches;
return totalMatches;
}
if (currSum == sum)
return 1;
return 0;
}
console.log(numSignWays([1, 1, 1], 3));
但是我在此代码中收到错误“ undefined”
function howManySquares(n) {
return helper(n, {});
}
function helper(n, hash) {
if (hash.hasOwnProperty(n))
return hash[n];
if (n <= 3)
return n;
res = n;
for (let i = 2; i < n + 1; i++) {
tmp = i * i;
if (tmp > n) {
break;
} else {
res = Math.min(res, 1 + helper(n - tmp));
}
}
hash[n] = res;
return res;
}
console.log(howManySquares(18));
预期输出为2。