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 =
return
Given array A =
return
Given array A =
return
挑战
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]
代码:
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; } };
相关文章推荐
- Lintcode: Majority Number III
- LintCode笔记(1)——硬币排成线
- **[Lintcode]Majority Number III
- LintCode-Majority Number III
- 【LintCode】Coins in a Line 硬币排成行
- *[Lintcode] Best Time to Buy and Sell Stock III
- lintcode-硬币排成一条线
- lintcode---43. 最大子数组 III
- LintCode-硬币排成线 II
- [LintCode]Majority Number III
- 硬币排成线 III
- LintCode 151 买卖股票的最佳时机 III
- lintcode:数字组合III
- 打劫房屋 III-LintCode
- 单词拆分 III-LintCode
- [LintCode] Coins in a Line II 一条线上的硬币之二
- [LintCode] 619 Binary Tree Longest Consecutive Sequence III 二叉树最长连续序列 III
- lintcode-84-落单的数 III
- LintCode:M-硬币排成线 II
- LintCode:主元素 III