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

Commit b5a46d9

Browse files
Tushar RoyTushar Roy
Tushar Roy
authored and
Tushar Roy
committed
Add BFS method for perfect square qs
1 parent 1ed843b commit b5a46d9

File tree

1 file changed

+53
-1
lines changed

1 file changed

+53
-1
lines changed

‎src/com/interview/dynamic/MinimumNumberOfPerfectSquares.java‎

Lines changed: 53 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,22 @@
11
package com.interview.dynamic;
22

3+
import java.util.*;
4+
35
/**
6+
* Date 10/19/2016
7+
* @author Tushar Roy
8+
*
9+
* Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, ...) which sum to n.
10+
* For example, given n = 12, return 3 because 12 = 4 + 4 + 4; given n = 13, return 2 because 13 = 4 + 9.
11+
*
12+
* Solution 1 - Using DP similar to coin change problem with infinite supply
13+
* Solution 2 - Using a BFS. Put all perfect squares in queue. Then considering each as a node try adding
14+
* another perfect square and see if we can get n. Keep doing this in BFS fashion till you hit the number.
15+
*
416
* https://leetcode.com/problems/perfect-squares/
517
*/
618
public class MinimumNumberOfPerfectSquares {
7-
public int numSquares(int n) {
19+
public int numSquaresUsingDP(int n) {
820
int count = (int)Math.ceil(Math.sqrt(n));
921

1022
int[] T = new int[n + 1];
@@ -22,4 +34,44 @@ public int numSquares(int n) {
2234
}
2335
return T[n];
2436
}
37+
38+
public int numSquaresUsingBFS(int n) {
39+
List<Integer> perfectSquares = new ArrayList<>();
40+
int i = 1;
41+
Queue<Integer> queue = new LinkedList<>();
42+
Set<Integer> visited = new HashSet<>();
43+
while (true) {
44+
int square = i * i;
45+
if (square == n) {
46+
return 1;
47+
}
48+
if (square > n) {
49+
break;
50+
}
51+
perfectSquares.add(square);
52+
queue.offer(square);
53+
visited.add(square);
54+
i++;
55+
}
56+
int distance = 1;
57+
while (!queue.isEmpty()) {
58+
int size = queue.size();
59+
distance++;
60+
for (int j = 0; j < size; j++) {
61+
int node = queue.poll();
62+
for (int square : perfectSquares) {
63+
int sum = node + square;
64+
if (sum == n) {
65+
return distance;
66+
} else if (!visited.contains(sum)) {
67+
visited.add(sum);
68+
queue.add(sum);
69+
} else if (sum > n) {
70+
break;
71+
}
72+
}
73+
}
74+
}
75+
return distance;
76+
}
2577
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /