DeTechn Blog

求给定数组中 N 个数相加之和为 sum 所有可能集合

求给定数组中 N 个数相加之和为 sum 所有可能集合,请补充以下代码

function fn(arr, n, sum) {}
function fun(arr, n, sum) {
  let result = [];
  if (arr.length < n) return -1;
  arr.sort((prev, next) => {
    return prev - next;
  });
  function getSum(arr, n, currSum, index, incArr = []) {
    for (let i = index; i < arr.length; i++) {
      let temp = currSum + arr[i];
      if (temp > sum) break;

      if (n > 1) {
        getSum(arr, n - 1, temp, i + 1, [arr[i], ...incArr]);
      }

      if (n === 1 && temp === sum) {
        result.push([arr[i], ...incArr]);
      }
    }
  }
  getSum(arr, n, 0, 0);
  return result;
}
function findSumNumbers(array, n, sum) {
  // 枚举所有n个数的组合,判断组合的和等于sum
  let result = [];
  const generateAll = function (index, collection, arr) {
    if (collection.length === n) {
      const s = collection.reduce((acc, c) => (acc += c), 0);
      if (s === sum) {
        result.push(collection);
      }
      return;
    }
    for (let i = 0; i < arr.length; i++) {
      generateAll(index + 1, collection.concat(arr[i]), arr.slice(i + 1));
    }
  };
  generateAll(0, [], array.slice(0));
  return result;
}

findSumNumbers([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 2, 10);

findSumNumbers([1, 0, -1, 0, -2, 2], 4, 0);

当前页面是本站的「Google AMP」版。查看和发表评论请点击:完整版 »