赞
踩
- <span style="font-size:18px;"><span style="font-size:18px;">//普通递归
- int sum(int start,int end)
- {
- if(start>end)
- return 0;
- else
- return start+sum(start+1,end);
- }</span></span>
- <span style="font-size:18px;"><span style="font-size:18px;">//尾递归
- int tail_sum(int seed,int start,int end)
- {
- if(start>end)
- return seed;
- else
- return tail_sum(seed+start,start+1,end);
- }
- </span></span>
- <span style="font-size:18px;"><span style="font-size:18px;">X sum(X seed, X start, X end){
- if(start<end)
- return seed;
- else
- return sum(seed+start, start+1, end);
- }</span></span>
另外,不是所有的递归都可以变成尾递归的。
最后附上Fibonacci数列求解的尾递归:
- <span style="font-size:18px;"><span style="font-size:18px;">//普通递归
- int Fibonacci(int n)
- {
- if(n<2)
- return n;
- else
- return Fibonacci(n-2)+Fibonacci(n-1);
- }
-
- //尾递归
- int tail_Fibonacci(int n,int a1,int a2)
- {
- if(n==0)
- return a1;
- else
- return tail_Fibonacci(n-1,a1+a2,a1);
- }</span></span>
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。