青蛙跳台阶,1步或者2步,找规律即可,发现和斐波那契数列很相似,稍微改动一下代码
注意递归出口不为0了
class Solution
{
//尾递归
public static int Fibonacci(int n)
{
return Fibonacci(n, 1, 2);
}
private static int Fibonacci(int n, int acc1, int acc2)
{
if (n == 1) return acc1;//出口改为1
else return Fibonacci(n - 1, acc2, acc1 + acc2);
}
//迭代
//private static int Fibonacci(int n)
//{
// if (n <= 2) return n;
// int num1 = 1, num2 = 2;
// int currentnum = 0;
// for (int i = 3; i <= n; i++)
// {
// currentnum = num1 + num2;
// num1 = num2;
// num2 = currentnum;
// }
// return currentnum;
//}
static void Main(string[] args)
{
Console.Write(Fibonacci(5));
}
}