【问题标题】:Get all (number of) combinations of an array获取数组的所有(数量)组合
【发布时间】:2021-05-20 19:37:05
【问题描述】:

从昨天开始我就一直在尝试完成这个,虽然还没有运气。我找到了解决方案,但我想要完成的任务总是略有不同。

我试图获得所有可能的组合,有点像这样:combination_k,但我也希望相同的项目与自身配对,所以给出以下内容:

输入[1, 4, 5]2(组合数)应返回:

[1, 1], [1, 4], [1, 5], [4, 4], [4, 5], [5, 5]

输入 [1, 4, 5]3 应该返回:

[1, 1, 1], [1, 1, 4], [1, 1, 5], [1, 4, 4], [1, 4, 5], [4, 4, 4], [4, 4, 5], [5, 5, 5], [5, 5, 4], [5, 5, 1](顺序不重要)。

我一直在调整combination_k,它让我足够远,它可以与2一起使用,但是当我提供3作为参数时它就不起作用了。

const combinations = getAllCombinations([1, 4, 5], 2);
// combinations = [1, 1], [1, 4], [1, 5], [4, 4], [4, 5], [5, 5]

欢迎任何提示!

【问题讨论】:

  • 你能发布你为实现 2 所做的工作吗?
  • 为什么[1, 5, 5] 不在您的预期输出中?
  • 是的,我已经做了几件事,但实现这一目标的最简单和最短的方法是将第 121 行更改为 tailcombs = k_combinations(set.slice(i), k - 1); @combination_k
  • @Nick 我看到我错过了那个,哎呀!我已经编辑了我的初始帖子并将该项目添加到预期列表中。
  • Here is a dynamical programming solution with no recursion。 JS中的递归在一定范围后可能会导致调用栈溢出问题。

标签: javascript arrays


【解决方案1】:

这个问题通常被称为k-combinations with repeats

这是一个依赖递归来获得所需结果的解决方案:

const combinations = (array, r) => {
  const result = [];
  const fn = (array, selected, c, r, start, end) => {
    if (c == r) {
      result.push([...selected]);
      return;
    }
    
    for (let i = start; i <= end; i++) {
      selected[c] = array[i];
      fn(array, selected, c + 1, r, i, end);
    }
  }
  
  fn(array, [], 0, r, 0, array.length - 1);
  return result;
}

console.log(combinations([1, 4, 5], 3));

【讨论】:

    【解决方案2】:

    您提供的代码的修改版本:

    function getAllCombinations(arr, n) {
      if (n <= 0) return [];
      if (n === 1) return [...arr];
    
      return arr.reduce((acc, cur, i) => {
        const head = arr.slice(i, i + 1);
        const combinations = getAllCombinations(arr.slice(i), n - 1)
          .map(x => head.concat(x));
        return [...acc, ...combinations];
      }, []);
    }
    
    console.log(getAllCombinations([1, 4, 5], 2).join('|'));
    console.log(getAllCombinations([1, 4, 5], 3).join('|'));

    【讨论】:

    • 我投票是因为你的答案比我的更实用。看着我们!让世界变得更美好,一次评论:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多