当前位置:网站首页>C语言 函数递归
C语言 函数递归
2022-08-04 00:08:00 【卷饼85】
函数递归
函数递归就是自己调用自己来解决问题。
在解决一个问题时,通过对问题进行一次次的分解得到所对应的值,然后再将每次解决的问题所得的值进行合并,最终解决问题。

优点
代码简洁清晰,可读性好
缺点
1.时间和空间消耗较大。每一次函数调用都需要在栈中分配空间,往栈里面存入和取出数据都需要时间。
2.递归会造成栈溢出的问题。栈的大小是有限的,如果函数递归深度太大,所需要的内存空间可能会大于栈区的内存,会造成栈溢出的情况。
习题
1到n的和
1到n的和
int add(int n)
{
if (n == 1)return 1;
return add(n - 1) + n;
}
int main()
{
printf("%d",add(4));
return 0;
}
运行结果:
斐波那契数列
斐波那契数列
int fei(int n)
{
if (n == 1 || n == 2)return 1;
return fei(n - 1) + fei(n - 2);
}
int main()
{
printf("%d",fei(6));
return 0;
}
运行结果:
二分查找递归
二分查找递归
int BinarySearch0(int*nums,int target,int begin,int end)
{
int mid = begin + (end-begin) / 2;
if (begin > end)return -1;
if (nums[mid] > target)return BinarySearch0(nums, target, begin, mid - 1);
else if (nums[mid] < target)return BinarySearch0(nums, target, mid + 1, end);
else if (nums[mid] == target)return mid;
return {
};
}
int main()
{
int nums[] = {
1,2,3,4,6,7,8,9};
printf("%d",BinarySearch0(nums,6,0,7));//打印出6所在的下标
return 0;
}
运行结果:
倒着打印数字
递归打印数字
void a(int n)
{
if (n != 0)
{
printf("<%d>", n % 10);
a(n / 10);
}
}
int main()
{
a(123123123);
return 0;
}
运行结果:
边栏推荐
猜你喜欢

Why Flutter Flutter of tutorials is the best choice for business?

Using matlab to solve the linear optimization problem based on matlab dynamic model of learning notes _11 】 【

Nanoprobes丨Nanogold-抗体和链霉亲和素偶联物

RSS订阅微信公众号初探-feed43

LYVE1抗体丨Relia Tech LYVE1抗体解决方案

RSS feeds WeChat public - feed43 asain

The problem of disorganized data output by mnn model

Justin Sun was invited to attend the 36氪 Yuan Universe Summit and delivered a keynote speech

pcl点云数据 转化为 Eigen::Map

Flutter教程之为什么 Flutter 是创业的最佳选择?
随机推荐
Apple told Qualcomm: I bought a new campus for $445 million and may plan to speed up self-development of baseband chips
DataBinding下的RecycleView适配器Adapter基类
带你造轮子,自定义一个随意拖拽可吸边的悬浮View组件
POE交换机全方位解读(上)
【超详细】手把手教你搭建MongoDB集群搭建
leetcode/子串中不能有重复字符的最长子串
XSLT – 服务器端概述
搭建好pytorch环境后,pip和conda指令不能用
超级完美版布局有快捷键,有背景置换(解决opencv 中文路径问题)
Nanoprobes 棕榈酰纳米金相关说明书
简单了解下 TCP,学习握手和挥手以及各种状态到底是怎么样的
机器学习——库
The longest substring that cannot have repeating characters in a leetcode/substring
sqlnet.ora文件与连接认证方式的小测试
Talking about the future development direction of my country's industrial parks
The super perfect layout has shortcut keys and background replacement
Free自由协议系统开发
[Miscellaneous] How to install the specified font into the computer and then use the font in the Office software?
重新认识浏览器的渲染过程
第1章:初识数据库与MySQL----MySQL安装