Skip to content

Commit 97fd69e

Browse files
committed
Add solution #279
1 parent a74dbb0 commit 97fd69e

File tree

2 files changed

+28
-0
lines changed

2 files changed

+28
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -222,6 +222,7 @@
222222
274|[H-Index](./0274-h-index.js)|Medium|
223223
275|[H-Index II](./0275-h-index-ii.js)|Medium|
224224
278|[First Bad Version](./0278-first-bad-version.js)|Medium|
225+
279|[Perfect Squares](./0279-perfect-squares.js)|Medium|
225226
282|[Expression Add Operators](./0282-expression-add-operators.js)|Hard|
226227
283|[Move Zeroes](./0283-move-zeroes.js)|Easy|
227228
290|[Word Pattern](./0290-word-pattern.js)|Easy|

solutions/0279-perfect-squares.js

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
/**
2+
* 279. Perfect Squares
3+
* https://leetcode.com/problems/perfect-squares/
4+
* Difficulty: Medium
5+
*
6+
* Given an integer n, return the least number of perfect square numbers that sum to n.
7+
*
8+
* A perfect square is an integer that is the square of an integer; in other words, it is
9+
* the product of some integer with itself. For example, 1, 4, 9, and 16 are perfect squares
10+
* while 3 and 11 are not.
11+
*/
12+
13+
/**
14+
* @param {number} n
15+
* @return {number}
16+
*/
17+
var numSquares = function(n) {
18+
const dp = new Array(n + 1).fill(0).map((_, i) => !i ? 0 : Infinity);
19+
20+
for (let i = 1; i <= n; i++) {
21+
for (let j = 1; j * j <= i; j++) {
22+
dp[i] = Math.min(dp[i], dp[i - j * j] + 1);
23+
}
24+
}
25+
26+
return dp[n];
27+
};

0 commit comments

Comments
 (0)