forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.cpp
53 lines (39 loc) · 1.12 KB
/
main.cpp
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
48
49
50
51
52
53
/// Source : https://leetcode.com/problems/divisor-game/
/// Author : liuyubobobo
/// Time : 2019-04-13
#include <iostream>
#include <vector>
using namespace std;
/// Dynamic Programming
/// Time Complexity: O(n^2)
/// Space Complexity: O(n)
class Solution {
public:
bool divisorGame(int N) {
vector<int> dp(N + 1, -1);
return dfs(N, dp, true);
}
private:
bool dfs(int x, vector<int>& dp, bool isAlice){
if(x == 1) return isAlice ? false : true;
if(dp[x] != -1) return dp[x];
if(isAlice){
for(int i = 1; i * i <= x; i ++)
if(x % i == 0 && dfs(x - i, dp, false))
return dp[x] = true;
return dp[x] = false;
}
else{
for(int i = 1; i * i <= x; i ++)
if(x % i == 0 && !dfs(x - i, dp, true))
return dp[x] = false;
return dp[x] = true;
}
}
};
int main() {
cout << Solution().divisorGame(2) << endl; // true
cout << Solution().divisorGame(3) << endl; // false
cout << Solution().divisorGame(9) << endl; // false
return 0;
}