-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathsolution.ts
More file actions
41 lines (29 loc) · 755 Bytes
/
solution.ts
File metadata and controls
41 lines (29 loc) · 755 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
/*
* @lc app=leetcode id=279 lang=javascript
*
* [279] Perfect Squares
*/
const history: Record<number, number> = {};
// @lc code=start
/**
* @param {number} n
* @return {number}
*/
const numSquares = (n: number): number => {
// * dp ['68 ms', '97.17 %', '35.8 MB', '100 %']
const sqrtN = n ** 0.5;
const intSqrtN = Math.floor(sqrtN);
// * for just square number
if (sqrtN == intSqrtN) return 1;
// * ---------------- rest cases
let restMin: number = Infinity;
for (let i = intSqrtN; i > 0; i--) {
const rest = n - i ** 2;
if (!history[rest]) history[rest] = numSquares(rest);
restMin = Math.min(restMin, history[rest]);
}
// * for add-ups
return restMin + 1;
};
// @lc code=end
export { numSquares };