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 | Input: n = 12 |
Example 2
1 | Input: n = 13 |
💡 Intuition
This is a dynamic programming problem.
- Define
dp[i]= minimum number of perfect squares to sum toi. - 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 | class Solution { |
⏱ 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 Breaklc-322— Coin Change