嵌套for循环递归

Nested for loops recursion

本文关键字:递归 循环 for 嵌套      更新时间:2023-10-16

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