Leetcode 279. Perfect Squares (Medium) (cpp)
Tag: Dynamic Programming, Breadth-first Search, Math
Difficulty: Medium
/*
279. Perfect Squares (Medium)
Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, ...) which sum to n.
For example, given n = 12, return 3 because 12 = 4 + 4 + 4; given n = 13, return 2 because 13 = 4 + 9.
*/
class Solution {
public:
int numSquares(int n) {
if (n <= 0) return 0;
static vector<int> table{(0)};
while (table.size() <= n) {
int _size = table.size();
int temp = INT_MAX;
for (int i = 1; i * i <= _size; i++)
temp = min(temp, table[_size - i * i] + 1);
table.push_back(temp);
}
return table[n];
}
};