您的位置:首页 > 其它

玩转递归

2015-12-30 21:56 316 查看
所谓递归可以说成函数调函数

如我们 return eat3(n - 1) * 2 + 2 (大圣吃桃子)

下面上图看递归原理:

递归牵连到两个概念 压栈和出栈



看完图相信大家应该懂了是怎么回事(这么压栈内存可不少哦)

下面上吃桃子的代码:

class Program
{
static void Main(string[] args)
{
Console.WriteLine(eat3(10));
}

public static int eat2(int n)
{
int a = 1;

if (n == 1)
{
return 1;
}
else
{
a = eat2(n - 1) * 2 + 2;
}

return a;
}

//递归
public static int eat3(int n)
{
//eat2方法简写三目表达式
return n == 1 ? 1 : eat3(n - 1) * 2 + 2;
}

//递推
public static int eat(int n)
{
int a = 1;

for (int i = 2; i <=n; i++)
{
a = 2 * a + 2;
}

return a;

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: