递归是一种解决问题的有效方法,在递归过程中,函数将自身作为子例程调用
你可能想知道如何实现调用自身的函数。诀窍在于,每当递归函数调用自身时,它都会将给定的问题拆解为子问题。递归调用继续进行,直到到子问题无需进一步递归就可以解决的地步。
为了确保递归函数不会导致无限循环,它应具有以下属性:
以相反的顺序打印字符串。
C#写法
class Program
{
static void Main(string[] args)
{
//将字符串逆向输出,利用递归方式
string str = "asdfgh";
char[] strchar = str.ToCharArray();
helper(0,strchar);
Console.ReadKey();
}
public static void helper(int index,char[] str)
{
if (str == null || index >= str.Length)
{
return;
}
helper(index + 1, str);
Console.WriteLine(str[index]);
}
}
原文:https://www.cnblogs.com/Alex-Mercer/p/12100677.html