数据结构学习----递归(Java实现)
2014-12-10 11:46 雪夜&流星 阅读(224) 评论(0) 编辑 收藏 举报普通递归:
package com.clarck.datastructure.digit; public class Digit_9 { /** * 递归方法 * * @param i * @param n */ static void count(int i, int n) { if (i < n) { System.out.print(i + " "); count(i + 1, n); } System.out.print(i + " "); } public static void main(String[] args) { int i, j, n = 9; for (i = 1; i <= n; i++) { for (j = n; j > i; j--) { System.out.print(" "); } count(1, i); System.out.println(); } } }
运行结果:
1 1 2 1 1 2 3 2 1 1 2 3 4 3 2 1 1 2 3 4 5 4 3 2 1 1 2 3 4 5 6 5 4 3 2 1 1 2 3 4 5 6 7 6 5 4 3 2 1 1 2 3 4 5 6 7 8 7 6 5 4 3 2 1 1 2 3 4 5 6 7 8 9 8 7 6 5 4 3 2 1
求 n!:
package com.clarck.datastructure.digit; /** * 求 n! * * @author clarck * */ public class Factorial { /** * 求阶乘n!,递归方法 * * @param n * @return */ public static int factorial(int n) { if (n < 0) { throw new java.lang.IllegalArgumentException("n = " + n); } if (n == 0 || n == 1) { return 1; } return n * factorial(n - 1); } public static void main(String[] args) { int n = 5; System.out.println(n + "!=" + factorial(n)); System.out.println(n + "!=" + toString(n) + factorial(n)); } public static String toString(int n) { if (n > 0) { return toString(n, ""); } throw new java.lang.IllegalArgumentException("n = " + n); } public static String toString(int n, String str) { if (n == 0 || n == 1) { return ""; } else { str += n + "*" + (n -1) + "!=" + toString(n - 1, str); return str; } } }
运行结果:
5!=120 5!=5*4!=4*3!=3*2!=2*1!=120
用递归算法求Fibonacci数列:
package com.clarck.datastructure.digit; /** * 用递归算法求Fibonacci数列 * * @author clarck * */ public class Fibonacci { /** * 返回Fibonacci数列第n项,递归方法 * @param n * @return */ public static int fib(int n) { if (n < 0) { throw new java.lang.IllegalArgumentException("n = " + n); } if (n == 0 || n == 1) { return n; } return fib(n - 2) + fib(n - 1); } public static void main(String[] args) { for (int i = 0; i <= 24; i++) { System.out.print(fib(i) + " "); } System.out.println(); } }
运行结果:
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946 17711 28657 46368
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本