1
1
package com .interview .dynamic ;
2
2
3
+ import java .util .*;
4
+
3
5
/**
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
+ *
4
16
* https://leetcode.com/problems/perfect-squares/
5
17
*/
6
18
public class MinimumNumberOfPerfectSquares {
7
- public int numSquares (int n ) {
19
+ public int numSquaresUsingDP (int n ) {
8
20
int count = (int )Math .ceil (Math .sqrt (n ));
9
21
10
22
int [] T = new int [n + 1 ];
@@ -22,4 +34,44 @@ public int numSquares(int n) {
22
34
}
23
35
return T [n ];
24
36
}
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
+ }
25
77
}
0 commit comments