几种常用的算法(递归,Top-n)
//C#用递归算法实现:一列数的规则如下: 1、1、2、3、5、8、13、21、34,求第30位数是多少
public static int GetPosValue(int pos)
{
//第1位、第2位,实际上索引是0、1
if (pos == 0 || pos == 1) //我们习惯上,位置使用索引(从0开始,0视为是第1位)
{
return 1;
}
int posValue = GetPosValue(pos - 1) + GetPosValue(pos - 2);
return posValue;
}
//1+2+3+4+5+.....n
public static int SumValue(int n)
{
if (n == 1)
{
return 1;
}
int sum_n = SumValue(n - 1) + n;
return sum_n;
}
原理:亦即n!=1×2×3×...×(n-1)×n。阶乘亦可以递归方式定义:0!=1,n!=(n-1)!×n。
public static int Factorial(int n)
{
if (n == 0 || n == 1)
{
return 1;
}
else
{
// 递归调用:当前数n乘以前面所有数的阶乘
return n * Factorial(n - 1);
}
}
//计算数组中所有元素之和
public static int ArraySum(int[] arr, int index)
{
if (index >= arr.Length)
{
// 基本情况:数组为空或者已经遍历完所有元素
return 0;
}
else
{
// 递归调用:当前元素加上剩余元素的总和
return arr[index] + ArraySum(arr, index + 1);
}
}
//获取数组中元素值是top-n的元素
int max1=0,max2=0;
public int GetTop2(int[] array)
{
for (int i = 0; i < array.Length; i++)
{
if (array[i] > max2)
{
max1 = max2;
max2 = array[i];
}
}
return max1;
}
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 没有源码,如何修改代码逻辑?
· PowerShell开发游戏 · 打蜜蜂
· 在鹅厂做java开发是什么体验
· 百万级群聊的设计实践
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战
2020-09-22 图像处理的灰度化和二值化
2019-09-22 对象、流、磁盘、序列化、反序列化等概念之间的关系