leetcode877 Stone Game
思路:贪心策略显然不对 因此需要列举所有情况 使用dp降低时间复杂度(此题有数学解 可以证明Alex一定赢)
alex和lee是在头和尾轮流拿石头 dp记录时需要记录两端 因此是一个二维数组dp[ left][right];
以[5,3,4,5]为例 如果拿左边 剩下的是[3,4,5] ,dp[left][right] =piles[left]+dp[left+1][right] ? 因为Lee还要拿 所以 这个是不对的 剩下的[3,4,5]lee要拿掉头尾中的一个,实际上alex只能在[3,4]或者[4,5]中选取 因此dp[left][right] =piles[left]+max(dp[left+1][right-1],dp[left+2,right])
如果拿右边的 dp[left][right]=piles[right]+max(dp[left+1][right-1],dp[left,right-2]);
在左右中选一个最大的:
dp[left][right]=max(piles[left]+max(dp[left+1][right-1]dp[left+2,right]),piles[right]+max(dp[left+1][right-1],dp[left,right-2]);
class Solution {
public:
using VV=vector<vector<int> >;
using V=vector<int>;
bool stoneGame(vector<int>& piles) {
int n=piles.size();
vector<vector<int> > dp(n,vector<int>(n,-1));
vector<int> alex(n,0);// 标记alex选取的pile 可以不要 用piles总和减去alexsum
int alexsum=maxsum(dp,alex,piles,0,n-1);
int leesum=0;// 可以不用这么写 直接piles总和减去alexsum即可
for(int i=0;i<n;++i){
if(!alex[i]){
leesum+=piles[i];
}
}
//cout<<alexsum<<' '<<leesum<<endl;
if(alexsum>leesum){
return true;
}else{
return false;
}
}
int maxsum(VV& dp,V& alex,V& piles,int left,int right){
if(left>right)
return 0;
if(dp[left][right]!=-1)
return dp[left][right];
int choosel=piles[left]+max(maxsum(dp,alex,piles,left+1,right-1),maxsum(dp,alex,piles,left+2,right));
int chooser=piles[right]+max(maxsum(dp,alex,piles,left+1,right-1),maxsum(dp,alex,piles,left,right-2));
if(choosel>chooser){
alex[left]=1;
dp[left][right]=choosel;
}else{
dp[left][right]=chooser;
alex[right]=1;
}
//cout<<"dp["<<left<<"]"<<"["<<right<<"]="<<dp[left][right];
return dp[left][right];
}
};