6、查找目标组合

2021-09-28  本文已影响0人  杀破狼real

给定第一个数组和目标结果,找出数组中和为目标结果的组合

const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13];
const target = 15;

function findNumGroup(arr) {
  const result = [];

  function findNum(arr, o) {
    if (!o) {
      o = arr.shift();
    }
  
    for (let i = 0; i < arr.length; i++) {
      let temp = [...arr];
  
      const o_arr = String(o).split(',').map(item => Number(item));
      const sum = o_arr.reduce((a, b) => a + b);
      if (sum + temp[i] === target) {
        result.push(o + ',' + temp[i]);
      }
  
      if (i !== temp.length - 1) {
        const p = o + ',' + temp[i];
        temp = temp.slice(i + 1);
        findNum(temp, p);
      }
  
      if (String(o).length === 1 && i === arr.length - 1) {
        o = arr.shift();
        findNum(arr, o);
      }
    }
  }
  
  findNum(arr);
  return result;
}

const result = findNumGroup(arr);
console.log('result :>> ', result);
// result :>>  [
//   '1,2,3,4,5', '1,2,3,9', '1,2,4,8',
//   '1,2,5,7',   '1,2,12',  '1,3,4,7',
//   '1,3,5,6',   '1,3,11',  '1,4,10',
//   '1,5,9',     '1,6,8',   '2,3,4,6',
//   '2,3,10',    '2,4,9',   '2,5,8',
//   '2,6,7',     '2,13',    '3,4,8',
//   '3,5,7',     '3,12',    '4,5,6',
//   '4,11',      '5,10',    '6,9',
//   '7,8'
// ]
上一篇下一篇

猜你喜欢

热点阅读