Lecture 4 (中)
来源:互联网 发布:java 算术运算符 编辑:程序博客网 时间:2024/06/09 22:40
函数的递归调用:在调用一个函数的过程中又出现直接或间接调用该函数本身(无终止的自身调用)
递归定义的要素:基础 归纳
直接递归:
int f(int x)
{
int y,z;
......
z=f(y);
....
return (2*z);
}
间接递归:
int f1(int x)
{
int y,z;
......
z=f2(y);
....
return (2*z);
}
int f2(int t)
{
int a,c;
......
c=f1(a);
....
return (3+c);
}
递归实例:
int main ()
{
int m;
cin>>m;
void story (int n); 调用前声明
story (m); 函数调用
return 0;
}
void story (int n)
{
if (n>0)
{
cout<<"从前有座山,山里有座庙,庙里有个老和尚,他在说:"<<endl;
story(n-1);
}
}
例:求n!
int main ()
{
int m;
long x;
cin>>m;
long fact(int n);
x=fact(m); 数据类型要相同,都为long
cout<<x<<endl; 一定要显示到屏幕,否则无输出
return 0;
}
long fact(int n)
{
long f;
if (n==1) ==为比较运算符,不可写为赋值运算符=,否则结果恒为1
f=1;
else
f=n*fact(n-1);
return f;
}
也可以将if用for语句替代:
Fact=1;
For (i=1;i<=n;i++)
Fact*=i;
例题:
int main ()
{
int i=1234;
void f(int n);
f(i);
cout<<endl;
return 0;
}
void f(int n)
{
if(n==0)
return;
else
{
cout<<n%10; 输出4321
f(n/10);
cout<<n%10; 输出1234
return;
}
}
输出结果为43211234
与正常递归类似,只是递归和返回过程中都有输出显示
改为else
{
f(n/2);
cout<<n%2;
return;
} 后,得到的为输入n 的二进制数 (除二取余法)
递归思维解决问题:
楼梯有n阶台阶,上楼可以一步上1阶,也可以一步上2阶,编一程序计算共有多少种不同的走法
设n阶台阶的走法数为F(n)
F(n)= 1 ,n=1;
2 ,n=2;
F(n-1)+F(n-2),n>2;
假设最后一次上台阶,可以走一步,还剩F(n-1)个走法;可以走2步,还剩F(n-2)个走法
斐波那契数列的递归表示:
0,1,1,2,3,5,8,13,21,……
F(n)=F(n-1)+F(n-2) n>2
汉诺塔:将n个盘子由座子A通过B移到C,一次只能移一个,每个座子上始终大盘在下,小盘在上
思路:如果只有一个盘子,则直接由A移到C;
如果n>1,则将n-1个盘子先通过C移到B,再将最大的盘子从A移到C,最后将n-1个盘子从B经过A移到C
void move(int n,char A,char B,char C)
{
if(n==1)
cout<<A<<"-->"<<C<<endl;
else
{
move(n-1,A,C,B);
cout<<A<<"-->"<<C;
move(n-1,B,A,C);
}
}
void main ()
{
int n;
cin>>n;
move(n,'A','B','C');
}
- Lecture 4 (中)
- Lecture 4
- Lecture 4(下)
- CS224D Lecture 4 札记
- cs231n Lecture 4
- CS109 Lecture 4
- Lecture 4 Microphone
- Lecture 4 Microphone Sensitivity
- CS107-Lecture 4-Note
- Lecture 4: Code View
- Lecture 6 数组(中)
- Unit 4-Lecture 3: Independence
- Unit 4-Lecture 5: Expectation
- Unit 4-Lecture 4: Random Variable
- Stanford ML - Lecture 4 - Neural Networks: Representation
- Lecture 4 函数与预处理 (上)
- CS229 Lecture Notes(4): Generative Learning Algorithm
- Unit 1-Lecture 4:Logical & Propositions
- UVA 714 Copying Books 最大值最小化问题 (贪心 + 二分)
- 编程小技巧
- 冒泡排序算法(C#实现)
- process 0
- Counting Squares
- Lecture 4 (中)
- 快速排序算法(C#实现)
- Lecture 4(下)
- web.xml中部署servlet注意
- ViewController的使用及生命周期
- POJ 3254 Corn Fields (状态压缩DP)
- Cuts the cake
- 快逸V5设置两表关联
- 去掉list中重复的记录