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 }
原文:https://www.cnblogs.com/katsu2017/p/13270274.html