Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit9ac845e

Browse files
Create 279-Perfect-Squares.java
1 parent17eb20b commit9ac845e

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

‎java/279-Perfect-Squares.java‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
//This is a BFS based approach.
2+
//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).
3+
4+
classSolution {
5+
publicintnumSquares(intn) {
6+
Queue<Integer>q =newLinkedList<>();
7+
//add visited array so we don't go to values which we have traversed already (similar to dp) otherwise this will give tle
8+
HashSet<Integer>visited =newHashSet<>();
9+
intans =0;
10+
q.offer(n);
11+
while (!q.isEmpty()) {
12+
intsize =q.size();
13+
for (inti =0;i<size;i++) {
14+
intcur =q.poll();
15+
if (cur ==0)returnans;
16+
for (intj =1;j<=cur/j;j++) {
17+
if (!visited.contains(cur-j*j)) {
18+
q.offer(cur-j*j);
19+
visited.add(cur-j*j);
20+
}
21+
}
22+
}
23+
ans++;
24+
}
25+
return -1;
26+
}
27+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp