|
| 1 | +## 题目地址 |
| 2 | +https://leetcode.com/problems/perfect-squares/description/ |
| 3 | + |
| 4 | +## 题目描述 |
| 5 | + |
| 6 | + |
| 7 | +``` |
| 8 | +Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, ...) which sum to n. |
| 9 | +
|
| 10 | +Example 1: |
| 11 | +
|
| 12 | +Input: n = 12 |
| 13 | +Output: 3 |
| 14 | +Explanation: 12 = 4 + 4 + 4. |
| 15 | +Example 2: |
| 16 | +
|
| 17 | +Input: n = 13 |
| 18 | +Output: 2 |
| 19 | +Explanation: 13 = 4 + 9. |
| 20 | +
|
| 21 | +``` |
| 22 | + |
| 23 | +## 思路 |
| 24 | + |
| 25 | +直接递归处理即可,但是这种暴力的解法很容易超时。如果你把递归的过程化成一棵树的话(其实就是递归树), |
| 26 | +可以看出中间有很多重复的计算。 |
| 27 | + |
| 28 | +如果能将重复的计算缓存下来,说不定能够解决时间复杂度太高的问题。 |
| 29 | + |
| 30 | +> 递归对内存的要求也很高, 如果数字非常大,也会面临爆栈的风险,将递归转化为循环可以解决。 |
| 31 | +
|
| 32 | +如果使用DP,其实本质上和递归 + 缓存 差不多。 |
| 33 | + |
| 34 | +## 关键点解析 |
| 35 | + |
| 36 | +- 如果用递归 + 缓存, 缓存的设计很重要 |
| 37 | +我的做法是key就是n,value是以n为起点,到达底端的深度。 |
| 38 | +下次取出缓存的时候用当前的level + 存的深度 就是我们想要的level. |
| 39 | + |
| 40 | +## 代码 |
| 41 | + |
| 42 | +```js |
| 43 | +/* |
| 44 | + * @lc app=leetcode id=279 lang=javascript |
| 45 | + * |
| 46 | + * [279] Perfect Squares |
| 47 | + * |
| 48 | + * https://leetcode.com/problems/perfect-squares/description/ |
| 49 | + * |
| 50 | + * algorithms |
| 51 | + * Medium (40.98%) |
| 52 | + * Total Accepted: 168.2K |
| 53 | + * Total Submissions: 408.5K |
| 54 | + * Testcase Example: '12' |
| 55 | + * |
| 56 | + * Given a positive integer n, find the least number of perfect square numbers |
| 57 | + * (for example, 1, 4, 9, 16, ...) which sum to n. |
| 58 | + * |
| 59 | + * Example 1: |
| 60 | + * |
| 61 | + * |
| 62 | + * Input: n = 12 |
| 63 | + * Output: 3 |
| 64 | + * Explanation: 12 = 4 + 4 + 4. |
| 65 | + * |
| 66 | + * Example 2: |
| 67 | + * |
| 68 | + * |
| 69 | + * Input: n = 13 |
| 70 | + * Output: 2 |
| 71 | + * Explanation: 13 = 4 + 9. |
| 72 | + */ |
| 73 | + |
| 74 | +const mapper = {}; |
| 75 | + |
| 76 | +function d(n, level) { |
| 77 | + |
| 78 | + if (n === 0) return level; |
| 79 | + |
| 80 | + let i = 1; |
| 81 | + const arr = []; |
| 82 | + |
| 83 | + while(n - i * i >= 0) { |
| 84 | + const hit = mapper[n - i * i]; |
| 85 | + if (hit) { |
| 86 | + arr.push(hit + level); |
| 87 | + } else { |
| 88 | + const depth = d(n - i * i, level + 1) - level; |
| 89 | + mapper[n - i * i] = depth; |
| 90 | + arr.push(depth + level); |
| 91 | + } |
| 92 | + i++; |
| 93 | + } |
| 94 | + |
| 95 | + return Math.min(...arr); |
| 96 | +} |
| 97 | +/** |
| 98 | + * @param {number} n |
| 99 | + * @return {number} |
| 100 | + */ |
| 101 | +var numSquares = function(n) { |
| 102 | + return d(n, 0); |
| 103 | +}; |
| 104 | +``` |
0 commit comments