-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDivisorGame.java
More file actions
39 lines (33 loc) · 844 Bytes
/
DivisorGame.java
File metadata and controls
39 lines (33 loc) · 844 Bytes
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
// https://leetcode.com/problems/divisor-game/
// #math #dynamic-programming
class Solution {
public boolean divisorGame(int n) {
/*
dp[n] = true/false
true: start with n, the first player always wins
false: start with n, always loses
dp[1] = false
dp[2] = true
dp[3] = false
A:
dp[n] -> x, n % x == 0 dp[n-x].
=> for (1 -> n) {
x => n % x == 0 && dp[n-x] == false ? => break => true;
}
bottom up
*/
boolean[] dp = new boolean[n + 1];
dp[1] = false;
for (int i = 2; i <= n; i++) {
//
int limit = i / 2;
for (int j = 1; j <= limit; j++) {
if (i % j == 0 && dp[i - j] == false) {
dp[i] = true;
break;
}
}
}
return dp[n];
}
}