loading

279. Perfect Squares — Step-by-Step Visualization

mediumLeetCode #279MathDynamic ProgrammingBFS

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 (e.g., `1, 4, 9, 16, ...`). **Example 1:** Input: `n = 12` Output: `3` Explanation: `12 = 4 + 4 + 4` **Example 2:** Input: `n = 13` Output: `2` Explanation: `13 = 4 + 9`

Algorithm Pattern

Unbounded Knapsack (Coin Change variant)

Key Idea

Treat perfect squares as 'coins'. dp[i] = min squares that sum to i. For each i, try every j where j² ≤ i and take dp[i - j²] + 1.

Step-by-Step Approach

  1. Initialize dp[0] = 0, dp[1..n] = ∞.
  2. For each i from 1 to n:
  3. Try every j = 1, 2, … while j² ≤ i.
  4. dp[i] = min(dp[i], dp[i - j²] + 1).
  5. Return dp[n].

Common Gotchas

  • Inner loop iterates j (not j²) — increment j by 1, stopping when j*j > i.
  • This is identical to Coin Change where coins are [1, 4, 9, 16, …].

Related Problems