Skip to content

Commit f7f94b2

Browse files
add a solution for 279
1 parent 490edbd commit f7f94b2

File tree

2 files changed

+62
-0
lines changed

2 files changed

+62
-0
lines changed

src/main/java/com/fishercoder/solutions/_279.java

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,4 +37,35 @@ public int numSquares(int n) {
3737
}
3838
}
3939

40+
public static class Solution3 {
41+
/**
42+
* My completely original DP solution on 10/14/2021.
43+
* <p>
44+
* Again, once you use a pen and paper to visualize your thought process, the idea flows out very quickly.
45+
* Thinking without a pen and paper is a waste of time in most cases! :)
46+
*/
47+
public int numSquares(int n) {
48+
int[] dp = new int[n + 1];
49+
for (int i = 1; i <= n; i++) {
50+
int x = (int) Math.sqrt(i);
51+
if (Math.pow(x, 2) == i) {
52+
dp[i] = 1;
53+
} else {
54+
dp[i] = i;
55+
int left = 1;
56+
int right = i - 1;
57+
while (left < right) {
58+
dp[i] = Math.min(dp[i], dp[left] + dp[right]);
59+
left++;
60+
right--;
61+
}
62+
if (left == right && i % left == 0) {
63+
dp[i] = Math.min(dp[i], (i / left) * dp[left]);
64+
}
65+
}
66+
}
67+
return dp[n];
68+
}
69+
}
70+
4071
}
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
package com.fishercoder;
2+
3+
import com.fishercoder.solutions._279;
4+
import com.fishercoder.solutions._340;
5+
import org.junit.BeforeClass;
6+
import org.junit.Test;
7+
8+
import static org.junit.Assert.assertEquals;
9+
10+
public class _279Test {
11+
private static _279.Solution1 solution1;
12+
private static _279.Solution2 solution2;
13+
private static _279.Solution3 solution3;
14+
15+
@BeforeClass
16+
public static void setup() {
17+
solution1 = new _279.Solution1();
18+
solution2 = new _279.Solution2();
19+
solution3 = new _279.Solution3();
20+
}
21+
22+
@Test
23+
public void test1() {
24+
int n = 9;
25+
int expected = 1;
26+
assertEquals(expected, solution1.numSquares(n));
27+
assertEquals(expected, solution2.numSquares(n));
28+
assertEquals(expected, solution3.numSquares(n));
29+
}
30+
31+
}

0 commit comments

Comments
 (0)