Algorithm Day85 - Perfect Squares

🧩 Problem Description

Given an integer n, return the least number of perfect square numbers (e.g., 1, 4, 9, 16, ...) which sum to n.


💬 Examples

Example 1

1
2
3
Input: n = 12
Output: 3
Explanation: 12 = 4 + 4 + 4

Example 2

1
2
3
Input: n = 13
Output: 2
Explanation: 13 = 4 + 9

💡 Intuition

This is a dynamic programming problem.

  • Define dp[i] = minimum number of perfect squares to sum to i.
  • Transition:
1
dp[i] = min(dp[i - j*j] + 1) for all j where j*j <= i
  • Base case: dp[0] = 0.

Alternatively, this problem can also be solved with BFS (treating each remainder as a node).


🔢 Java Code (DP Approach)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public int numSquares(int n) {
int[] dp = new int[n + 1];
Arrays.fill(dp, Integer.MAX_VALUE);
dp[0] = 0;

for (int i = 1; i <= n; i++) {
for (int j = 1; j * j <= i; j++) {
dp[i] = Math.min(dp[i], dp[i - j * j] + 1);
}
}
return dp[n];
}
}

⏱ Complexity Analysis

  • Time: O(n * sqrt(n)) — for each i, we check all squares up to sqrt(i).
  • Space: O(n) — DP array.

✍️ Summary

  • Classic DP problem.
  • Transition: dp[i] = min(dp[i - j*j] + 1).
  • Alternative BFS solution possible.

Related problems

  • lc-139 — Word Break
  • lc-322 — Coin Change