forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain3.cpp
More file actions
52 lines (37 loc) · 1.12 KB
/
Copy pathmain3.cpp
File metadata and controls
52 lines (37 loc) · 1.12 KB
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
/// Source : https://leetcode.com/problems/stone-game/description/
/// Author : liuyubobobo
/// Time : 2018-08-03
#include <iostream>
#include <vector>
using namespace std;
/// Memory Search
/// Just use 2d dp array and consider two moves by each player together:)
///
/// Time Complexity: O(n^2)
/// Space Complexity: O(n^2)
class Solution {
public:
bool stoneGame(vector<int>& piles) {
int n = piles.size();
vector<vector<int>> dp(n, vector<int>(n, INT_MIN));
return play(piles, 0, n-1, dp) > 0;
}
private:
int play(const vector<int>& piles, int l, int r, vector<vector<int>>& dp){
if(l + 1 == r)
return abs(piles[l] - piles[r]);
if(dp[l][r] != INT_MIN)
return dp[l][r];
return dp[l][r] = max(
abs(piles[l] - piles[l + 1]) + play(piles, l + 2, r, dp),
abs(piles[l] - piles[r]) + play(piles, l + 1, r - 1, dp));
}
};
void print_bool(bool res){
cout << (res ? "True" : "False") << endl;
}
int main() {
vector<int> piles1 = {5, 3, 4, 5};
print_bool(Solution().stoneGame(piles1));
return 0;
}