c++ - 嵌套 for 循环递归

标签 c++ for-loop recursion coordinates

我查阅了很多地方并试图了解如何通过递归获得任意数量的嵌套 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 

我只是想不通哪里出了问题。任何帮助找出错误或什至另一种生成坐标的方法将不胜感激。谢谢!

最佳答案

Non-recursive solution基于 add-with-carry:

#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;
}

Recursive solution ,从您的原始代码中抢救:

#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;
}

关于c++ - 嵌套 for 循环递归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25070766/

相关文章:

C++ 重载 : Overloading the [][] operator

c++ - Arduino Uno不想写变量

python - 如何让 CMake 编译包含 Boost Local Functions 的源文件

c++ - 在 C/C++ 中自动调用函数

PHP for 循环显示奇怪的结果

java - 将(BST 的)迭代层序遍历转换为递归实现

c++ - while 比 for 快吗?

java - 使用增强型 for 循环时的 IndexOutOfBoundsException

python - 递归错误 : maximum recursion depth exceeded while getting the str of an object

haskell - 埃拉托斯特尼筛无限列表