Fibonacci数列不同实现方式效率比较
1 /** 2 * 普通递归,效率低下,大部分值都被重复计算多遍 3 * 时间复杂度:O(2^n) 4 * 5 * n=50时,值:12586269025,花费36s 6 * 7 */ 8 @Test 9 public void recursive() { 10 long st = System.currentTimeMillis(); 11 System.out.println(testRecursive(50)); 12 System.out.println("cost Seconds: " + (System.currentTimeMillis() - st) / 1000); 13 } 14 15 private long testRecursive(int n) { 16 if (n == 1 || n == 2) { 17 return 1; 18 } 19 return testRecursive(n - 1) + testRecursive(n - 2); 20 } 21 22 /** 23 * 递归 + cache 24 * 时间复杂度:O(n) 25 * 空间复杂度:O(n) 26 * 27 * n=50时,值:12586269025,花费0s 28 */ 29 30 @Test 31 public void cache() { 32 long st = System.currentTimeMillis(); 33 Map<Long, Long> cache = new HashMap<>(); 34 System.out.println(testCache(50L, cache)); 35 System.out.println("cost Seconds: " + (System.currentTimeMillis() - st) / 1000); 36 } 37 38 private Long testCache(Long n, Map<Long, Long> cache) { 39 if (n == 1 || n == 2) { 40 return 1L; 41 } 42 if (cache.containsKey(n)) { 43 return cache.get(n); 44 } 45 46 long val = testCache(n - 1, cache) + testCache(n - 2, cache); 47 cache.put(n, val); 48 return val; 49 } 50 51 /** 52 * 自底向上 + cache 53 * 时间复杂度:O(n) 54 * 空间复杂度:O(n) 55 * 56 * n=50时,值:12586269025,花费0s 57 */ 58 @Test 59 public void dp() { 60 long st = System.currentTimeMillis(); 61 System.out.println(testDp(50)); 62 System.out.println("cost Seconds: " + (System.currentTimeMillis() - st) / 1000); 63 } 64 65 private long testDp(int n) { 66 Map<Integer, Long> dpCache = new HashMap<>(); 67 if (n == 1 || n == 2) { 68 return 1; 69 } 70 dpCache.put(1, 1L); 71 dpCache.put(2, 1L); 72 for (int i = 3; i <= n; i++) { 73 dpCache.put(i, dpCache.get(i - 1) + dpCache.get(i - 2)); 74 } 75 return dpCache.get(n); 76 } 77 78 /** 79 * 自底向上 + 空间复杂度为O(1) 80 * 时间复杂度:O(n) 81 * 空间复杂度:O(1) 82 * 83 * 84 * n=50时,值:12586269025,花费0s 85 */ 86 @Test 87 public void dp2() { 88 long st = System.currentTimeMillis(); 89 System.out.println(testDp2(50)); 90 System.out.println("cost Seconds: " + (System.currentTimeMillis() - st) / 1000); 91 } 92 93 private long testDp2(int n) { 94 if (n == 1 || n == 2) { 95 return 1; 96 } 97 long pre = 1; 98 long after = 1; 99 long tmp; 100 for (int i = 3; i <= n; i++) { 101 tmp = pre + after; 102 pre = after; 103 after = tmp; 104 } 105 return after; 106 }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 25岁的心里话
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用