算法知识-14-递归

递归的概念

递归是一种直接或间接调用自身函数或者方法的算法思想。它将一个复杂的问题分解为一个与原问题相似但规模更小的子问题,通过不断地重复这个过程,直到子问题变得简单到可以直接求解。

图示说明:

代码示例:

cpp 复制代码
int i = 0;
void fun() {
    cout << "进入下一层" << endl;
    i++;
    if (i < 5)
        fun();
    cout << "回归上一层" << endl;
}

fun()函数内部首先输出 "进入下一层",然后变量i自增。

然后条件判断if (i < 5),如果条件成立,则递归调用fun()函数。

最后,当递归调用结束后,输出 "回归上一层"。

cout << "进入下一层" << endl;和i++;这两句代码在每次递归进入下一层时执行。

cout << "回归上一层" << endl;这行代码在每次递归返回上一层时执行。

if (i < 5)用来限制递进的条件,被称为递归出口,当i不再小于 5 时,递归停止。

下面的问题不是都要用递归完成,可以使用递推

5177 递归版台阶问题升级

cpp 复制代码
#include <bits/stdc++.h>
using namespace std;
int a(int x){
    if(x==1||x==2) return x;
    if(x==3) return 4;
    return a(x-1)+a(x-2)+a(x-3);
}
int n;
int main(){
    cin>>n;
    cout<<a(n);
    return 0;
}

3103土地分割

就是找最大公约数

可以使用辗转相除法‌:将较大的数除以较小的数,将余数作为新的被除数,反复进行除法运算,直到余数为0时,上一次的除数即为最大公约数。这种方法效率较高,适用于较大的数。

cpp 复制代码
#include<bits/stdc++.h>
using namespace std;
long long n,m;
long long gcd(long long a,long long b){
    return b==0?a:gcd(b,a%b);
}
int main(){
	cin>>n>>m;
    cout<<gcd(n,m);
	return 0;
}

3102输出序列第n个数

cpp 复制代码
#include <bits/stdc++.h>
using namespace std;
int f(int x){
	if(x==1) return 1;
    return f(x-1)+2;
}
int n;
int main(){
    cin>>n;
    cout<<f(n);
	return 0;
}

3101青蛙跳

cpp 复制代码
#include <bits/stdc++.h>
using namespace std;
int f(int x){
    if(x==1||x==2) return x;
	return f(x-1)+f(x-2);
}
int n;
int main(){
    cin>>n;
    cout<<f(n);
	return 0;
}

3100兔子繁殖问题

cpp 复制代码
#include <bits/stdc++.h>
using namespace std;
int f(int x){
    if(x==1||x==2) return 1;
	return f(x-1)+f(x-2);
}
int main(){
    cout<<f(12);
	return 0;
}

3099递归求阶乘

cpp 复制代码
#include <bits/stdc++.h>
using namespace std;
int f(int x){
    if(x==1) return 1;
	return f(x-1)*x;
}
int n;
int main(){
    cin>>n;
    cout<<f(n);
	return 0;
}

3098递归版台阶问题

cpp 复制代码
#include <bits/stdc++.h>
using namespace std;
int f(int x){
    if(x==1||x==2) return x;
	return f(x-1)+f(x-2);
}
int n;
int main(){
    cin>>n;
    cout<<f(n);
	return 0;
}

3097累加和

cpp 复制代码
#include <bits/stdc++.h>
using namespace std;
int f(int x){
    if(x==1) return 1;
	return f(x-1)+x;
}
int main(){
    cout<<f(10);
	return 0;
}

3096用递归实现输出

cpp 复制代码
#include <bits/stdc++.h>
using namespace std;
void a(int n){
	if(n>1) a(n-1);
	cout<<n<<' ';
} 
int main(){
    a(10);
	return 0;
}

1674倒序数

cpp 复制代码
#include <bits/stdc++.h>
using namespace std;
void f(int x){
    int t=x%10;
    cout<<t;
    if(x>9) f(x/10);
}
int n;
int main(){
    cin>>n;
    f(n);
	return 0;
}
相关推荐
二进制person25 分钟前
Java SE--方法的使用
java·开发语言·算法
OneQ6661 小时前
C++讲解---创建日期类
开发语言·c++·算法
JoJo_Way1 小时前
LeetCode三数之和-js题解
javascript·算法·leetcode
.30-06Springfield1 小时前
人工智能概念之七:集成学习思想(Bagging、Boosting、Stacking)
人工智能·算法·机器学习·集成学习
凌肖战3 小时前
力扣网C语言编程题:在数组中查找目标值位置之二分查找法
c语言·算法·leetcode
weixin_478689764 小时前
十大排序算法汇总
java·算法·排序算法
luofeiju4 小时前
使用LU分解求解线性方程组
线性代数·算法
学不动CV了4 小时前
数据结构---线性表理解(一)
数据结构
SKYDROID云卓小助手5 小时前
无人设备遥控器之自动调整编码技术篇
人工智能·嵌入式硬件·算法·自动化·信号处理
ysa0510305 小时前
数论基础知识和模板
数据结构·c++·笔记·算法