创建排列组合以达到目标数字,但重复使用提供的 JavaScript 数字


我们需要编写一个 JavaScript 函数,该函数将数组中的数字作为第一个参数,将目标数字作为第二个参数。

此函数应返回原始数组中所有子数组的数组,其元素之和等于目标数字。我们可以使用单个数字两次来达到总和。

例如 −

如果输入数组和数字为 −

const arr = [1, 2, 4];
const sum = 4;

则输出应为 −

const output = [
   [1, 1, 1, 1],
   [1, 1, 2],
   [2, 2],
   [4]
]

示例

const arr = [1, 2, 4];
const sum = 4;
const getCombinations = (arr = [], sum) => {
   const result = [];
   const pushElement = (i, t) => {
      const s = t.reduce(function (a, b) {
      return a + b;
      }, 0);
      if (sum === s) {
         result.push(t);
         return;
      };
      if (s > sum || i === arr.length) {
         return;
      };
      pushElement(i, t.concat([arr[i]]));
      pushElement(i + 1, t);
   }
   pushElement(0, []);
   return result;
};
console.log(getCombinations(arr, sum));

输出

控制台中的输出为 −

[ [ 1, 1, 1, 1 ], [ 1, 1, 2 ], [ 2, 2 ], [ 4 ] ]

更新于: 21-11-2020

139 次浏览

开启您的 职业生涯

完成课程获得认证

开始
广告
© . All rights reserved.