结合重复

Combination with repetition

本文关键字:结合      更新时间:2023-09-26

我正在寻找一种方法来获得与数组摄入的所有可能的组合,所以如果我们有[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]. 

我看了其他几个帖子,比如这里的这个:https://stackoverflow.com/a/9960925/1328107但他们似乎都停止了所有的组合,如

[ 1, 2, 3 ], [ 1, 3, 2 ],[ 2, 1, 3 ], [ 2, 3, 1 ], [ 3, 1, 2 ], [ 3, 2, 1 ].

回溯就可以了:

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
}

一些例子:

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 */