根据结果和集合长度获取原数组中所有符合的集合

发布时间 2023-10-07 15:58:58作者: 爱编程的小苏苏
// 计算数字之和

const nums = [-1, 0, 1, 2, 3]

function countNums(num, nums, length) {
function getSum(data) {
let sum = 0;
for (let value of data) {
sum += value;
}
return sum
}
function getNumbers(source, count, isPermutation = true) {
//如果只取一位,返回数组中的所有项,例如 [ [1], [2], [3] ]
let currentList = source.map((item) => [item]);
if (count === 1) {
return currentList;
}
let result = [];
//取出第一项后,再取出后面count - 1 项的排列组合,并把第一项的所有可能(currentList)和 后面count-1项所有可能交叉组合
for (let i = 0; i < currentList.length; i++) {
let current = currentList[i];
//如果是排列的方式,在取count-1时,源数组中排除当前项
let children = [];
if (isPermutation) {
children = getNumbers(source.filter(item => item !== current[0]), count - 1, isPermutation);
} else {
//如果是组合的方法,在取count-1时,源数组只使用当前项之后的
children = getNumbers(source.slice(i + 1), count - 1, isPermutation);
}
for (let child of children) {
result.push([...current, ...child]);
}
}
return result;
}
const result = getNumbers(nums, length, false)
const nRes = []
for (const numbers of result) {
const sum = getSum(numbers)
if (sum === num) {
nRes.push(numbers)
}
}
return nRes
}

const result = countNums(2, nums, 3)
console.log(result)