LeetCode 0279. Perfect Squares Solution in Java, Python, C++, JavaScript, Go & Rust | Explanation + Code

CoderIndeed
0
0279. Perfect Squares

Description

Given an integer n, return the least number of perfect square numbers that sum to n.

A perfect square is an integer that is the square of an integer; in other words, it is the product of some integer with itself. For example, 1, 4, 9, and 16 are perfect squares while 3 and 11 are not.

 

Example 1:

Input: n = 12
Output: 3
Explanation: 12 = 4 + 4 + 4.

Example 2:

Input: n = 13
Output: 2
Explanation: 13 = 4 + 9.

 

Constraints:

  • 1 <= n <= 104

Solutions

Solution 1

PythonJavaC++GoTypeScriptRust
class Solution: def numSquares(self, n: int) -> int: m = int(sqrt(n)) f = [[inf] * (n + 1) for _ in range(m + 1)] f[0][0] = 0 for i in range(1, m + 1): for j in range(n + 1): f[i][j] = f[i - 1][j] if j >= i * i: f[i][j] = min(f[i][j], f[i][j - i * i] + 1) return f[m][n](code-box)

Solution 2

PythonJavaC++GoTypeScriptRust
class Solution: def numSquares(self, n: int) -> int: m = int(sqrt(n)) f = [0] + [inf] * n for i in range(1, m + 1): for j in range(i * i, n + 1): f[j] = min(f[j], f[j - i * i] + 1) return f[n](code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !