【发布时间】:2015-05-29 18:04:48
【问题描述】:
我不太确定这种打印顺序叫什么,因此称之为奇怪。
考虑以下示例:
1 3 5
2 6 7
预期输出:
1,2
1,6
1,7
3,2
3,6
3,7
5,2
5,6
5,7
或者这个例子:
1 2 3
4 5 6
7 8 9
输出:
1,4,7
1,4,8
1,4,9
1,5,7
1,5,8
1,5,9
... and so on.
我已经分析,对于任何给定的矩阵,可能的组合数量将是rows^columns。这是我的解决方案:
#include <iostream>
#include <vector>
#include <string>
#include <cstdlib>
#include <cstdio>
using namespace std;
void printAllPossibleCombinations(int** a, int h, int n, string prefix)
{
if (h == 0)
{
for (int i = 0; i < n; i++)
{
cout << prefix << a[0][i] << endl;
}
}
else
{
for (int i = 0; i < n; i++)
{
string recursiveString = prefix;
recursiveString.append(to_string(a[h][i]));
recursiveString.append(1, ',');
printAllPossibleCombinations(a, h-1, n, recursiveString);
}
}
}
int main()
{
int **a;
int m,n,k;
cout<<"Enter number of rows: ";
cin>>m;
a = new int*[m];
cout<<endl<<"Enter number of columns: ";
cin>>n;
for(int i=0;i<m;i++)
{
a[i] = new int [n];
}
for(int i=0;i<m;i++)
{
for(int j = 0; j < n;j++)
{
cout<<"Enter a[" << i << "][" << j<< "] = ";
cin>>a[i][j];
cout<<endl;
}
}
printAllPossibleCombinations(a, m-1, n, "");
return 0;
}
有没有一种简单且更优化的方法?请建议。
谢谢
【问题讨论】:
-
不清楚你想做什么。特别是,当超过 2 行时,您要打印什么?
-
我也会添加一个3*3矩阵的例子!!
-
那么,您想要按特定顺序的笛卡尔积吗?
-
与行的笛卡尔积(元素按特定顺序)有什么不同?
标签: c++ algorithm recursion dynamic-programming