欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 汽车 > 新车 > 蓝桥杯学习-12递归

蓝桥杯学习-12递归

2025/3/19 22:31:33 来源:https://blog.csdn.net/weixin_74143480/article/details/146303249  浏览:    关键词:蓝桥杯学习-12递归

12递归

1.概述

2.几个递归模板

(1)求阶乘

int f(int n){
if(n == 1) return 1;
return f(n-1) * n;
}

(2)斐波拉契序列

int f(int n){
if(n == 1 || n == 2) return n;
return f(n - 1) + f(n - 2);
}

例题一-蓝桥5194

image-20250316220322649

int f(int n){if(n == 0) return 1;if(n % 2 == 0) return f(n / 2)return f(n - 1) + 1;
}

例题二-蓝桥19880-组合数模板

image-20250316220759127

模板

int C(int n, int m){if(n == m || m == 0) return 1;return C(n-1,m-1) + C(n-1,m);
}
import java.util.Scanner;
// 1:无需package
// 2: 类名必须Main, 不可修改public class Main {static int t,n,m;public static void main(String[] args) {solve();}public static int C(int n, int m){if(n == m || m == 0) return 1;return C(n-1,m-1) + C(n-1,m);}public static void solve(){Scanner sc = new Scanner(System.in);//输入tt = sc.nextInt();for(int i = 0; i < t; i++){n = sc.nextInt();m = sc.nextInt();System.out.println(C(n,m));}sc.close();}
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词