嵌套for循环递归
Nested for loops recursion
我查阅了很多地方,并试图理解如何通过递归获得任意数量的嵌套for循环。但我的理解显然是错误的。
我需要在n维空间中以网格模式生成坐标。实际的问题有不同的坐标和不同的范围,但为了使事情更简单,我在下面的代码中使用了相同的整数步进坐标范围。
#include <iostream>
using namespace std;
void recursion(int n);
int main(){
recursion(3);
return 0;
}
void recursion(int n)
{
if(n!=0){
for(int x=1; x<4; x++){
cout<<x<<" ";
recursion(n-1);
}
}
else cout<<endl;
}
我想要,并且期望输出是:
1 1 1
1 1 2
1 1 3
1 2 1
1 2 2
1 2 3
1 3 1
1 3 2
1 3 3
2 1 1
2 1 2
2 1 3
2 2 1
2 2 2
2 2 3
2 3 1
2 3 2
2 3 3
3 1 1
3 1 2
3 1 3
3 2 1
3 2 2
3 2 3
3 3 1
3 3 2
3 3 3
相反,我得到的输出是
1 1 1
2
3
2 1
2
3
3 1
2
3
2 1 1
2
3
2 1
2
3
3 1
2
3
3 1 1
2
3
2 1
2
3
3 1
2
3
我就是不知道出了什么问题。任何帮助找出错误或甚至另一种方式来生成坐标将非常感激。谢谢! 基于加法进位的非递归解:
#include <iostream>
using namespace std;
bool addOne(int* indices, int n, int ceiling) {
for (int i = 0; i < n; ++i) {
if (++indices[i] <= ceiling) {
return true;
}
indices[i] = 1;
}
return false;
}
void printIndices(int* indices, int n) {
for (int i = n-1; i >= 0; --i) {
cout << indices[i] << ' ';
}
cout << 'n';
}
int main() {
int indices[3];
for (int i=0; i < 3; ++i) {
indices[i] = 1;
}
do {
printIndices(indices, 3);
} while (addOne(indices, 3, 3));
return 0;
}
递归解决方案,从原始代码中回收:
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
void recursion(int n, const string& prefix);
int main(){
recursion(3, "");
return 0;
}
void recursion(int n, const string& prefix)
{
if (n!=0) {
for(int x=1; x<4; x++){
ostringstream os;
os << prefix << x << ' ';
recursion(n-1, os.str());
}
}
else cout << prefix << endl;
}
根据Igor的注释,您需要一个增量函数。
让我们用一个std::vector
来表示每一个维度。即向量[0]是第一维,向量[1]是第二维,以此类推。
使用向量可以在没有任何硬编码数字的情况下确定维数。vector.size()将是维度数。
这里有一个函数让你开始:
void Increment_Coordinate(std::vector<int>& coordinates,
int max_digit_value,
int min_digit_value)
{
unsigned int digit_index = 0;
bool apply_carry = false;
do
{
apply_carry = false;
coordinates[digit_index]++; // Increment the value in a dimension.
if (coordinates[digit_index] > max_digit_value)
{
// Reset the present dimension value
coordinates[digit_index] = min_digit_value;
// Apply carry to next column by moving to the next dimension.
++digit_index;
apply_carry = true;
}
} while (apply_carry);
return;
}
编辑1 这只是一个基础。函数需要进行边界检查。
此函数不支持不同大小的维度。这留给读者或op做练习。
相关文章:
- 为什么在递归中使用循环会产生意想不到的结果?
- 无穷大而循环时具有递归函数
- 如何使用递归循环我的代码(当用户输入无效输入时,它会再次提示他们)?
- C++ 模板使用递归实现循环
- C++ 使用递归而不是 for 循环
- 递归应用 C++20 范围适配器会导致编译时无限循环
- 为什么这个递归函数会创建一个无限循环?
- 如何使用循环编写此递归
- 计算递归和时的无限循环
- 递归回溯打印长度为N的二进制数的所有组合,而不使用循环
- 递归导致程序崩溃,但 while 循环中的相同概念不是来自C++析构函数
- C++ 循环链表的递归基本情况
- 循环访问多个模板参数的递归模板函数
- 在 C++ 中用递归替换循环的 N 级
- 如果找不到解决方案,我如何留下递归循环,而不会打印任何东西
- 如何在C++中将基本嵌套循环转换为递归循环
- 在递归循环中条件修改的引用内存
- 递增迭代器并在递归循环中传递参数
- 当在有限递归循环中操作大型数组时,我应该在哪一点从堆栈切换到堆?
- 递归循环(c#)