C# 递归执行顺序

为了方便进一步理解递归,写了一个数字输出

class Program
{
    static void Main(string[] args)
    {
        int number = 5;
        RecursiveDecrease(number);
    }

    static void RecursiveDecrease(int n)
    {
        if (n > 0)
        {
            Console.WriteLine("Before recursive call do : " + n);
			RecursiveDecrease(n - 1);
			Console.WriteLine("After recursive call  do : " + n);
		}
	}
}

输出结果:

Before recursive call do : 5
Before recursive call do : 4
Before recursive call do : 3
Before recursive call do : 2
Before recursive call do : 1
After recursive call  do : 1
After recursive call  do : 2
After recursive call  do : 3
After recursive call  do : 4
After recursive call  do : 5

class Program
{
	static void Main(string[] args)
	{
		int number = 5;
		int[] ages ={1, 2, 3};
         RecursiveDecrease(number,ages);
    }



	static void RecursiveDecrease(int n,int[] age)
    {
        if (n > 0)
        {
            Console.WriteLine("Before recursive call do : " + n+ " array: "+string.Join(",",age));
			RecursiveDecrease(n - 1,age);
			Console.WriteLine("After recursive call one  do : " + n+ " array: "+string.Join(",",age));
			n=n+19;
			for (int i = 0; i < age.Length; i++)
			{
				age[i]=age[i]+10;
			}
			Console.WriteLine("After recursive call  two do : " + n+ " array: "+string.Join(",",age));
		}
	}
}

输出结果:

Before recursive call do : 5 array: 1,2,3
Before recursive call do : 4 array: 1,2,3
Before recursive call do : 3 array: 1,2,3
Before recursive call do : 2 array: 1,2,3
Before recursive call do : 1 array: 1,2,3
After recursive call one  do : 1 array: 1,2,3
After recursive call  two do : 20 array: 11,12,13
After recursive call one  do : 2 array: 11,12,13
After recursive call  two do : 21 array: 21,22,23
After recursive call one  do : 3 array: 21,22,23
After recursive call  two do : 22 array: 31,32,33
After recursive call one  do : 4 array: 31,32,33
After recursive call  two do : 23 array: 41,42,43
After recursive call one  do : 5 array: 41,42,43
After recursive call  two do : 24 array: 51,52,53

具体使用方法如下:

  • 定义一个递归函数,入参数和返回类型。
  • 在函数体内,编写递归停止条件和递归调用的语句。
  • 在递归调用前后,可以编写其他需要执行的代码

总结:

    递归的执行顺序是先进后出的,每次递归调用都会暂停当前的执行,进入到新的函数调用中执行,直到满足退出条件时递归结束,然后返回到上一层递归调用,继续执行后续的代码。

  1. 先进后出的场景使用包括但不限于:
  • 栈数据结构:递归函数的调用栈是一种典型的先进后出的结构,可以利用栈的特性实现一些需要后进先出的操作。
  • 深度优先搜索(DFS):在树或图的遍历过程中,可以使用递归实现深度优先搜索,先探索当前节点的子节点,再回溯到父节点的其他未探索子节点。
  • 解决复杂问题:递归可以将复杂问题分解成简单的子问题,并通过先解决子问题再合并的方式得到最终解。例如,递归可以用于计算斐波那契数列、阶乘、二叉树的高度等。
  • 反转操作:递归可以实现字符串、列表、数组等的反转操作,先处理最后一个元素,再处理前面的元素,从而实现先进后出的效果。
  • 7
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值