1、递归
关于递归的概念,我们都不陌生。简单的来说递归就是一个函数直接或间接地调用自身,是为直接或间接递归。一般来说,递归需要有边界条件、递归前进段和递归返回段。当边界条件不满足时,递归前进;当边界条件满足时,递归返回。用递归需要注意以下两点:(1) 递归就是在过程或函数里调用自身。(2) 在使用递归策略时,必须有一个明确的递归结束条件,称为递归出口。
1 int FibonacciRecursive(int n)
2 {
3 if( n < 2)
4 return n;
5 return (FibonacciRecursive(n-1)+FibonacciRecursive(n-2));
6 }
递归写的代码非常容易懂,完全是根据函数的条件进行选择计算机步骤。例如现在要计算n=5时的值,递归调用过程如下图所示:
2、尾递归
顾名思义,尾递归就是从最后开始计算, 每递归一次就算出相应的结果, 也就是说, 函数调用出现在调用者函数的尾部, 因为是尾部, 所以根本没有必要去保存任何局部变量. 直接让被调用的函数返回时越过调用者, 返回到调用者的调用者去。尾递归就是把当前的运算结果(或路径)放在参数里传给下层函数,深层函数所面对的不是越来越简单的问题,而是越来越复杂的问题,因为参数里带有前面若干步的运算路径。
尾递归是极其重要的,不用尾递归,函数的堆栈耗用难以估量,需要保存很多中间函数的堆栈。比如f(n, sum) = f(n-1) + value(n) + sum; 会保存n个函数调用堆栈,而使用尾递归f(n, sum) = f(n-1, sum+value(n)); 这样则只保留后一个函数堆栈即可,之前的可优化删去。
采用尾递归实现Fibonacci函数,程序如下所示:
1 int FibonacciTailRecursive(int n,int ret1,int ret2)
2 {
3 if(n==0)
4 return ret1;
5 return FibonacciTailRecursive(n-1,ret2,ret1+ret2);
6 }
例如现在要计算n=5时的值,尾递归调用过程如下图所示:
从图可以看出,为递归不需要向上返回了,但是需要引入而外的两个空间来保持当前的结果。
为了更好的理解尾递归的应用,写个程序进行练习。采用直接递归和尾递归的方法求解单链表的长度,C语言实现程序如下所示:
#include <stdio.h>
#include <stdlib.h>
typedef struct node
{
int data;
struct node* next;
}node,*linklist;
void InitLinklist(linklist* head)
{
if(*head != NULL)
free(*head);
*head = (node*)malloc(sizeof(node));
(*head)->next = NULL;
}
void InsertNode(linklist* head,int d)
{
node* newNode = (node*)malloc(sizeof(node));
newNode->data = d;
newNode->next = (*head)->next;
(*head)->next = newNode;
}
//直接递归求链表的长度
int GetLengthRecursive(linklist head)
{
if(head->next == NULL)
return 0;
return (GetLengthRecursive(head->next) + 1);
}
//采用尾递归求链表的长度,借助变量acc保存当前链表的长度,不断的累加
int GetLengthTailRecursive(linklist head,int *acc)
{
if(head->next == NULL)
return *acc;
*acc = *acc+1;
return GetLengthTailRecursive(head->next,acc);
}
void PrintLinklist(linklist head)
{
node* pnode = head->next;
while(pnode)
{
printf("%d->",pnode->data);
pnode = pnode->next;
}
printf("->NULL\n");
}
int main()
{
linklist head = NULL;
int len = 0;
InitLinklist(&head);
InsertNode(&head,10);
InsertNode(&head,21);
InsertNode(&head,14);
InsertNode(&head,19);
InsertNode(&head,132);
InsertNode(&head,192);
PrintLinklist(head);
printf("The length of linklist is: %d\n",GetLengthRecursive(head));
GetLengthTailRecursive(head,&len);
printf("The length of linklist is: %d\n",len);
system("pause");
}
程序测试结果如下图所示:
3、尾递归优化
Python和Java 不能尾递归优化,不做尾递归优化是为了抛出异常时有完整的stack trace。至于C++和C,优化是取决于编译器的,尾递归优化(tail call optimization特例)也是取决于编译器的。
Tail recursion can usually be transformed into a loop by the compiler, especially when accumulators are used.
// tail recursion
int fac_times (int n, int acc = 1) {
if (n == 0) return acc;
else return fac_times(n - 1, acc * n);
}
would compile to something like
// accumulator
int fac_times (int n) {
int acc = 1;
while (n > 0) {
acc *= n;
n -= 1;
}
return acc;
}
Both the current version of VC++ and GCC do tail call optimizations fairly well and even for mutually recursive calls. I bet the Intel compiler does, too.
Letting the compiler do the optimization is straightforward: Just switch on optimization for speed. But you do that anyway, right? ;-)
For MSVC, use /O2 or /Ox.
For GCC, use -O3
The easiest way to check if the compiler did the optimization (that I know of) is perform a call that would otherwise result in a stack overflow – or looking at the assembly output. However, you cann usually just assume that the compiler did the optimization.