您的位置:首页 > 其它

LintCode-硬币排成线 III

2015-05-22 23:47 288 查看
There are n coins in a line. Two players take turns to take a coin from one of the ends of the line until there are no more coins left. The player with the larger amount of money wins.

Could you please decide the first player will win or lose?

样例

Given array A =
[3,2,2]
,
return
true
.
Given array A =
[1,2,4]
,
return
true
.
Given array A =
[1,20,4]
,
return
false
.

挑战

Follow Up Question:
If n is even. Is there any hacky algorithm that can decide whether first player will win or lose in O(1) memory and O(n) time?

分析:这个一看感觉就是动态规划,但是状态确实有点难表示,可以用dp[i][j]表示从i到j这一段,先手的最大值和后手的最大值,用一个pair<int,int>保存,如果已知dp[i+1][j]和dp[i][j-1],那么就可以枚举两端确定dp[i][j]

代码:

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
int n = values.size();
vector<vector<pair<int,int> > > dp(n,vector<pair<int,int> >(n,make_pair(0,0)));
for(int len=1;len<=n;len++)
{
for(int i=0;i+len<=n;i++)
{
int j = i+len-1;
if(i==j)
dp[i][j] = make_pair(values[i],0);
else
{
pair<int,int> p1 = dp[i+1][j];
pair<int,int> p2 = dp[i][j-1];
if(p1.second+values[i]>p2.second+values[j])
{
dp[i][j] = make_pair(p1.second+values[i],p1.first);
}
else
{
dp[i][j] = make_pair(p2.second+values[j],p2.first);
}
}
}
}
if(dp[0][n-1].first>dp[0][n-1].second)
return true;
else
return false;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: