Perfect Squares

BFS by levels (or DP) — at each level subtract a perfect square, return the first level reaching 0.

Medium
Time O(n * sqrt(n)) Space O(n)
LeetCode
3 min read
dp bfs math

Problem#

Return the least number of perfect squares that sum to n.

Examples#

  • n=123 (4+4+4).
  • n=132 (4+9).

Constraints#

  • 1 <= n <= 10^4.

Approach#

DP: dp[i] = 1 + min(dp[i - k*k]) for all k*k <= i. dp[0] = 0.

Solution#

Perfect Squares
class Solution {
public:
int numSquares(int n) {
vector<int> dp(n + 1, INT_MAX);
dp[0] = 0;
for (int i = 1; i <= n; ++i)
for (int k = 1; k * k <= i; ++k)
if (dp[i - k * k] != INT_MAX)
dp[i] = min(dp[i], dp[i - k * k] + 1);
return dp[n];
}
};

Editorial#

This is unbounded knapsack flavored — each square can be reused. By Lagrange’s four-square theorem the answer is at most 4, so an O(sqrt n) math approach also exists, but the DP is the universal recipe.

Complexity#

  • Time: O(n * sqrt(n)).
  • Space: O(n).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.