-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0279.cpp
More file actions
25 lines (25 loc) · 812 Bytes
/
0279.cpp
File metadata and controls
25 lines (25 loc) · 812 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution {
private:
vector<int> generatePerfectSquares(int n) {
int upperBound = (int) sqrt(n) + 1;
vector<int> perfectSquares;
for (int i = 1; i <= upperBound; i++)
perfectSquares.push_back(i * i);
return perfectSquares;
}
public:
int numSquares(int n) {
vector<int> perfectSquares = generatePerfectSquares(n);
queue<pair<int,int>> q;
q.push({n, 0});
while (!q.empty()) {
pair<int,int> front = q.front(); q.pop();
for (int pSquare : perfectSquares) {
if (pSquare > front.first) break;
if (front.first - pSquare == 0) return front.second + 1;
q.push({front.first - pSquare, front.second + 1});
}
}
return -1;
}
};