首页 > 解决方案 > 获取数组的所有(数量)组合

问题描述

从昨天开始,我一直在努力做到这一点,尽管还没有运气。我找到了解决方案,在我想要完成的事情上总是有细微的差别。

我试图获得所有可能的组合,稍微像这样: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]

欢迎任何提示!

标签: javascriptarrays

解决方案


该问题通常被称为具有重复的 k 组合

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

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));


推荐阅读