与重复组合

Jar*_*tos 1 javascript

我正在寻找一种方法来获得所有可能的数组摄入组合,所以如果我们有[1,2,3]它会返回

[1,1,1],[1,1,2],[1,1,3],[1,2,2],[1,2,3],[1,3,3],[2,2,2],[2,2,3],[2,3,3],[3,3,3]. 
Run Code Online (Sandbox Code Playgroud)

我看过其他几篇文章,例如这里的这篇文章:https : //stackoverflow.com/a/9960925/1328107 但它们似乎都没有所有组合,即

[ 1, 2, 3 ], [ 1, 3, 2 ],[ 2, 1, 3 ], [ 2, 3, 1 ], [ 3, 1, 2 ], [ 3, 2, 1 ].
Run Code Online (Sandbox Code Playgroud)

任何帮助将不胜感激。

Ori*_*iol 9

回溯可以解决问题:

function combRep(arr, l) {
  if(l === void 0) l = arr.length; // Length of the combinations
  var data = Array(l),             // Used to store state
      results = [];                // Array of results
  (function f(pos, start) {        // Recursive function
    if(pos === l) {                // End reached
      results.push(data.slice());  // Add a copy of data to results
      return;
    }
    for(var i=start; i<arr.length; ++i) {
      data[pos] = arr[i];          // Update data
      f(pos+1, i);                 // Call f recursively
    }
  })(0, 0);                        // Start at index 0
  return results;                  // Return results
}
Run Code Online (Sandbox Code Playgroud)

一些例子:

combRep([1,2,3], 1); /* [
  [1], [2], [3]
] */
combRep([1,2,3], 2); /* [
  [1,1], [1,2], [1,3],
         [2,2], [2,3],
                [3,3]
] */
combRep([1,2,3], 3); /* [
  [1,1,1], [1,1,2], [1,1,3],
           [1,2,2], [1,2,3],
                    [1,3,3],

           [2,2,2], [2,2,3],
                    [2,3,3],

                    [3,3,3],
] */
combRep([1,2,3]); /* Same as above */
Run Code Online (Sandbox Code Playgroud)