如何在C++中将基本嵌套循环转换为递归 [英] How can I convert a basic nested loop to recursive in C++

查看:67
本文介绍了如何在C++中将基本嵌套循环转换为递归的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习递归,我正在寻找一个简单的示例,说明如何将这个基本的嵌套循环转换为递归函数。感谢您的意见: 编辑:我提供了转换嵌套循环的失败尝试。我还不能想象递归过程,但我的研究表明这就是递归格式。它不会显示输出,因为我不确定将COUT行放在哪里。

嵌套循环:

#include "stdafx.h"
#include<string>
#include<fstream>
#include<iomanip>
#include<vector>
#include<iostream>
#include<string.h>


using namespace std;

void recursive(int x, int y)
{
    for (int i = x; i > 0; i--)
        for (int j = y; j > 0; j--)
        {
            cout << i << " , " << j << endl;
        }
}
int main()
{
    int x, y;
    cout << "Enter 2 numbers:
";
    cin >> x >> y;
    recursive(x, y);
    return 0;
}

我尝试转换为递归函数:

void recursive(int start, int N)
{

    for (int x = start; x < N; x++)
    {

        recursive(x + 1, N);

    }



    for (int y = start; y < N; y++)
    {

        recursive(y + 1, N);

    }
}

int Main()
{
    recursive(0,3);
    return 0;
}

推荐答案

void recursive(int x, int y, int temp)
{
  if(x > 0) {
    if(y > 0) {
      cout << x << " " << y << endl;
      recursive(x,y-1,temp);
    }
    else {
      y = temp;
      recursive(x-1,y,temp);
    }
  }
}

到目前为止我得到的最好的解决方案,但是它需要额外的变量,才能让y返回到它的原始值。必须按recursive(x,y,y);

调用

这篇关于如何在C++中将基本嵌套循环转换为递归的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆