-------------------------------------资源来源于网络,仅供自学使用,如有侵权,联系我必删.
第一:
递归的数学思想
? 递归是一种数学上分而自治的思想
? 递归将大型复杂问题转化为与原问题相同但规模较小的问题进行处理
? 递归需要有边界条件
当边界条件不满足时 , 递归继续进行
当边界条件满足时 ,递归停止
第二:
斐波拉契数列递归解法
递归的一般表示法:
0 x = 1
f(x) = 1 x = 2
f(x - 1) + f(x - 2) x >= 3
#include <stdio.h>
int fibonacci(int n)
{
if( n > 1 )
{
return fibonacci(n-1) + fibonacci(n-2);//递归
}
else if( n == 1 )//边界条件
{
return 1;
}
else if( n == 0 )//边界条件
{
return 0;
}
}
int main()
{
int i = 0;
for(i=1; i<=10; i++)
{
printf("fibonacci(%d) = %d\n", i, fibonacci(i));
}
return 0;
}
第三:
strlen 递归解法
#include <stdio.h>
//字符串长度
int strlen(const char* s)
{
if( s == NULL )
{
return -1;
}
else if( *s == '\0' )
{
return 0;
}
else
{
return strlen(s+1) + 1;//递推关系,子串长度strlen(s+1)
}
}
int main()
{
printf("strlen(\"12345\") = %d\n", strlen("12345"));
printf("strlen(NULL) = %d\n", strlen(NULL));
printf("strlen(\"\") = %d\n", strlen(""));
return 0;
}
第四:
汉诺塔递归解法
#include <stdio.h>
void hanoi(int n, char a, char b, char c)
{
if( n > 0 )
{
if( n == 1 )
{
printf("%c -> %c\n", a, c);
}
else
{
hanoi(n-1, a, c, b);
printf("%c -> %c\n", a, c);
hanoi(n-1, b, a, c);
}
}
}
int main()
{
hanoi(8, 'a', 'b', 'c');
return 0;
}
第五:
全排列递归解法
#include <stdio.h>
void permutation(char s[], int b, int e)
{
if( (0 <= b) && (b <= e) )
{
if( b == e )//只有一个元素
{
printf("%s\n", s);
}
else
{
int i = 0;
for(i=b; i<=e; i++)
{
char c = s[b];
s[b] = s[i];
s[i] = c;
permutation(s, b+1, e);
c = s[b];
s[b] = s[i];
s[i] = c;
}
}
}
}
int main()
{
/*
char s[] = "abc";
permutation(s, 0, 2);
*/
char s[] = "abcd";
permutation(s, 0, 3);
return 0;
}
小结
? 递归是一种将问题分而自治的思想
? 用递归解决问题首先要建立递归的模型
? 递归解法必须要有边界条件 ,否则将死循环