-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy path1510. Stone Game IV.java
47 lines (40 loc) · 1.18 KB
/
1510. Stone Game IV.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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
// https://leetcode.com/problems/stone-game-iv/
// Further optimise the solution by removing currPlayer field and using dp
class Solution {
public boolean winnerSquareGame(int n) {
return winnerSquareGame(n, 0);
}
private boolean winnerSquareGame(int n, int currPlayer) {
if (n == 0) {
return false;
}
for (int i = 1; i <= Math.sqrt(n); i++) {
if (!winnerSquareGame(n - i * i, 1 - currPlayer)) {
return true;
}
}
return false;
}
}
class Solution {
public boolean winnerSquareGame(int n) {
Map<Integer, Boolean> dp = new HashMap<>();
return winnerSquareGame(n, dp);
}
private boolean winnerSquareGame(int n, Map<Integer, Boolean> dp) {
if (n == 0) {
return false;
}
if (dp.containsKey(n)) {
return dp.get(n);
}
for (int i = 1; i <= Math.sqrt(n); i++) {
if (!winnerSquareGame(n - i * i, dp)) {
dp.put(n, true);
return true;
}
}
dp.put(n, false);
return false;
}
}