以奇怪的顺序显示矩阵元素
Displaying Matrix elements in Strange Order
我不太清楚这种印刷顺序叫什么,所以我觉得很奇怪。
考虑以下示例示例:
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;
}
是否有一种更简单、更优化的方法来做这件事?请建议。
谢谢
正如你所说,在算法中有rows^columns
的东西需要物理打印,所以你不能比O(rows^columns)
算法做得更好,你的算法是最优的,因为你会得到
相关文章:
- 仅显示链表的最后一个元素
- 显示矢量的所有元素
- 在 QListView 中显示最后一个元素
- 在数组中显示第一个元素用户输入
- 尝试从列表中随机选取单个元素并将其显示为C++
- 为什么将函数的返回类型从结构节点*更改为void后,链表的元素没有显示create_ll和显示?
- 我有一个嵌套数组,它由另一个数组中的元素组成,这些元素分组为2.之后,我想显示每个元素的属性
- 数组:如何在指定索引之前显示数组的第一个和最后一个元素以及数组元素的差异?
- 代码是否有效.如果我想显示第一个元素?如果不是,那么 s.begin() 会返回什么?
- C++ rezing 动态数组最多可以处理一定数量的元素,但在某些时候会崩溃并显示错误 (0XC0000005)
- 编写一个递归功能,该功能采用数组并以相反顺序显示元素,而无需在末尾启动数组的索引
- 哪些更好的方法可以显示使用C STL创建的堆栈而不弹出每个元素的方法
- 用于显示矩阵元素的C 函数显示垃圾值
- 为什么这个 while 循环不显示第一个元素?
- 如何显示图形邻接列表的元素?
- 我写了此方法来删除链接列表的重复元素,但它显示了分段故障,原因
- 如何在不使用 C++ 函数的情况下显示链表中的元素
- strlen 显示数组元素的数量错误
- 更新模型/视图方案中 QXXXView (QTableView, QTreeView,..) 元素的显示工具提示
- Visual Studio 2013 C++:STL 容器的元素显示在调试器中