其实递归的应用很广,为毛老师当初只是一笔带过~~~~~~~~~~~~~~~~~~~~~~
=========
什么是递归:
简单地说递归就是自己调用自己
=========
【递归解决问题虽然会占用更多的堆栈,但是代码看起来很优美,符合问题的描述】
=========
什么时候使用递归:
问题本身采用递归描述,比如我们所熟悉的斐波那契数
如何使用递归:
1)找到终止条件
2)找到递归公式
例子:全排列问题:给出集合中所有元素的排列情况,例如(a, b, c )就有 abc , acb , bac , bca , cba , cab
递归条件:如果可以找到n - 1的所有全排列就可以找到所有n 的全排列,只要循环一下集合就可以
例子来源【数据结构 c 语言版】
#include <stdio.h>
#include <stdlib.h>
#define SWAP(x, y, t) ((t) = (x), (x) = (y), (y) = (t))
void perm(char[], int , int);
int main(int argc, char *argv[])
{
char list[3] = {'a','b','c'};
perm(list, 0, 2);
system("PAUSE");
return 0;
}
void perm(char *list, int i, int n)
{
int j , temp;
if(i == n)
{
for(j = 0 ; j <= n ; j ++)
printf("%c",list[j]);
printf(" ");
}else
{
for(j = i; j <= n; j ++)
{
SWAP(list[i],list[j],temp);
perm(list, i + 1, n);
SWAP(list[i],list[j],temp);
}
}
}
<span style="font-family: Arial, Helvetica, sans-serif;">【霍纳法则】</span>
int main(int argc, char *argv[])
{
int a[] = {1, 1, 1, 1};
int sum = horner(a, 0, 4, 2);
printf("%d",sum);
system("PAUSE");
return 0;
}
int horner(int a[], int i, int n, int x)
{
if(i == (n - 1))
return a[i]*x + a[i - 1];
else
return horner(a, ++i, n, x ) * x + a[i];
}