获取数组的所有(数量)组合

Cem*_*Cem 5 javascript arrays

从昨天开始,我一直在努力实现这一目标,尽管还没有运气。我找到了解决方案,其中我想要完成的事情总是略有不同。

我试图获得所有可能的组合,有点像这样: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]
Run Code Online (Sandbox Code Playgroud)

欢迎任何提示!

Rob*_*sen 5

该问题通常称为具有重复的 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));
Run Code Online (Sandbox Code Playgroud)