2 回答
TA贡献1865条经验 获得超7个赞
您可以在末尾修改trincot的解决方案filter
:
function findArrays(maxSize, maxSum) {
let arr = [];
let result = []; // <--- will collect all the subarrays
function recur(maxSum) {
let k = arr.length;
result.push([...arr]);
if (k === maxSize) return;
for (let i = 0; i <= maxSum; i++) {
arr[k] = i;
recur(maxSum - i);
}
arr.length = k;
}
recur(maxSum);
return result.filter(({ length }) => length == maxSize);
}
// demo
for (let arr of findArrays(3, 2))
console.log(JSON.stringify(arr));
TA贡献1824条经验 获得超6个赞
这是递归函数的非生成版本,它将给出您想要的结果。它计算出当前级别 ( 0..maxSum) 的所有可能值,然后将它们附加到数组的所有可能结果中size-1:
const findArrays = (size, maxSum) => {
let possibles = Array.from({
length: maxSum + 1
}, (_, i) => i);
if (size == 1) return possibles;
let result = [];
possibles.forEach(p => {
findArrays(size - 1, maxSum - p).forEach(a => {
result.push([p].concat(a));
});
});
return result;
}
console.log(findArrays(3, 2));
添加回答
举报