forked from neetcode-gh/leetcode
- Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0279-perfect-squares.java
28 lines (26 loc) · 1017 Bytes
/
0279-perfect-squares.java
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
26
27
28
//This is a BFS based approach.
//We can also do this problem similar to coin change but the Time and space complexity will remain same (Just an extra queue in this one stil linear space).
classSolution {
publicintnumSquares(intn) {
Queue<Integer> q = newLinkedList<>();
//add visited array so we don't go to values which we have traversed already (similar to dp) otherwise this will give tle
HashSet<Integer> visited = newHashSet<>();
intans = 0;
q.offer(n);
while (!q.isEmpty()) {
intsize = q.size();
for (inti = 0; i < size; i++) {
intcur = q.poll();
if (cur == 0) returnans;
for (intj = 1; j <= cur / j; j++) {
if (!visited.contains(cur - j * j)) {
q.offer(cur - j * j);
visited.add(cur - j * j);
}
}
}
ans++;
}
return -1;
}
}