Perfect Squares — LeetCode 279 Python Solution
- Problem
- #279
- Pattern
- Breadth-First Search
- Reading time
- 2 min
- Source
- leetcode.com
The problem
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.
Example
- Input
- n = 12
- Output
- 3
- Explanation
- 12 = 4 + 4 + 4.
Python solution
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]Complexity
| Measure | Complexity |
|---|---|
| Time | O(n·m) (typical) |
| Space | O(n·m) or optimized auxiliary |
Pattern: Breadth-First Search
Expand outward level by level, so the first time you arrive is the shortest way. LeetCode 279. Perfect Squares is filed here because LeetCode tags it Breadth-First Search, which is the vocabulary this hub collects.
The breadth-first search guide has the Python template for the pattern and the 233 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 279. Perfect Squares?
- LeetCode 279. Perfect Squares is rated Medium on LeetCode.
- What topics does LeetCode 279. Perfect Squares cover?
- LeetCode 279. Perfect Squares is tagged Breadth-First Search, Math and Dynamic Programming on LeetCode.