建立排列組合以達到目標數字,但重複使用提供的 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 次瀏覽

開啟您的 職業生涯

完成課程獲得認證

開始
廣告