生成2d向量中的所有元素组合

gny*_*his 4 c++ algorithm combinations

可能重复:
如何创建向量矢量的笛卡尔积?

我有一些逻辑问题,想出如何在二维矢量中生成元素的所有组合.在这里,我创建了一个2D矢量.两个维度的大小都不能假设.

#include <iostream>
#include <vector>

using namespace std;

int main() {
  srand(time(NULL));
  vector< vector<int> > array;

  // This creates the following:
  // array[0]: {0, 1, 2} 
  // array[1]: {3, 4, 5, 9} 
  // array[2]: {6, 7, 8} 
  for(int i=0; i<3; i++) { 
    vector<int> tmp;
    tmp.push_back((i*3)+0); tmp.push_back((i*3)+1); tmp.push_back((i*3)+2);
    if(i==1)
      tmp.push_back((i*3)+6);
    array.push_back(tmp);
  }
}
Run Code Online (Sandbox Code Playgroud)

创建向量后,我想输出所有可能的组合,如下所示:

  comb[0] = {0, 3, 6}
  comb[1] = {0, 3, 7}
  comb[2] = {0, 3, 8}
  comb[3] = {0, 4, 6}
  comb[4] = {0, 4, 7}
  comb[x] = {...}
Run Code Online (Sandbox Code Playgroud)

但是,我很难理解如何正确地构造循环结构,其中大小'array'和每个子数组中的元素是未知/动态的.

编辑1:不能假设有3个阵列.它们有array.size();)

Dan*_*her 6

未知大小的最简单方法是递归.

void combinations(vector<vector<int> > array, int i, vector<int> accum)
{
    if (i == array.size()) // done, no more rows
    {
        comb.push_back(accum); // assuming comb is global
    }
    else
    {
        vector<int> row = array[i];
        for(int j = 0; j < row.size(); ++j)
        {
            vector<int> tmp(accum);
            tmp.push_back(row[j]);
            combinations(array,i+1,tmp);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

最初打电话i = 0和空accum.