题目描述:
There are n coins with different value in a line. Two players take turns to take one or two coins from left side until there are no more coins left. The player who take the coins with the most value wins.
Could you please decide the first player will win or lose?
Given values array A = [1,2,2],
return true.
Given A = [1,2,4], return false.
这题的思路和#394类似:自己有两种选择:拿1或者拿2.但是对手的选择(1或者2)都是必须让自己拿的最少的。自己拿1的时候:对手的选择是dp[i - 3]和dp[i-2]里取最小;自己拿2的时候,对手在dp[i - 4]和 dp[i - 3]取最小。但是自己可以在拿1和拿2中选个最大值。
这题比较坑爹的是要注意初始化啊初始化。必须要从array的尾巴开始初始化和计算,因为从头看是有uncertainty的,我们是不知道到底应该怎么取的。
Mycode(AC = 11ms):
class Solution {
public:
/**
* @param values: a vector of integers
* @return: a boolean which equals to true if the first player will win
*/
bool firstWillWin(vector<int> &values) {
// write your code here
if (values.size() == 0) {
return false;
}
else if (values.size() <= 2) {
return true;
}
else if (values.size() == 3) {
return values[0] + values[1] > values[2];
}
else {
int n = values.size();
vector<int> dp(n + 1, 0);
// must initial from tail, because
// how to pick from head is uncertain
dp[1] = values[n - 1];
dp[2] = values[n - 1] + values[n - 2];
dp[3] = values[n - 3] + values[n - 2];
int total = values[0] + values[1] + values[2];
for (int i = 4; i <= values.size(); i++) {
total += values[i - 1];
dp[i] = max(min(dp[i - 4], dp[i - 3]) + values[n - i + 1] + values[n - i], // if player1 pick 2 coins
min(dp[i - 3], dp[i - 2]) + values[n - i]); // if player 1 pick 1 coin
}
return dp[n] > total - dp[n];
}
}
};
本文探讨了一种博弈论游戏算法,玩家轮流从一排不同价值的硬币中取走一枚或两枚,目标是获得最高总价值。文章通过示例说明了如何决定首位玩家是否能赢,并提供了一个实现该算法的C++代码示例。
363

被折叠的 条评论
为什么被折叠?



