算法设计与分析(十五):DP

Stone Game

Alex and Lee play a game with piles of stones. There are an even number of piles arranged in a row, and each pile has a positive integer number of stones piles[i].
The objective of the game is to end with the most stones. The total number of stones is odd, so there are no ties.
Alex and Lee take turns, with Alex starting first. Each turn, a player takes the entire pile of stones from either the beginning or the end of the row. This continues until there are no more piles left, at which point the person with the most stones wins.
Assuming Alex and Lee play optimally, return True if and only if Alex wins the game.

Example 1:

Input: [5,3,4,5]
Output: true
Explanation: 
Alex starts first, and can only take the first 5 or the last 5.
Say he takes the first 5, so that the row becomes [3, 4, 5].
If Lee takes 3, then the board is [4, 5], and Alex takes 5 to win with 10 points.
If Lee takes the last 5, then the board is [3, 4], and Alex takes 4 to win with 9 points.
This demonstrated that taking the first 5 was a winning move for Alex, so we return true.

Note:

  • 2 <= piles.length <= 500
  • piles.length is even.
  • 1 <= piles[i] <= 500
  • sum(piles) is odd.

本题要我们求在Alex先手取的情况下,判断Alex是否能够赢得比赛。

显然,我们可以用DP的思路寻求答案。假设dp[i][j]代表在i到j的区间中相较于对手多取得的石头数,由于要从2头取,那么有两种情况,取piles[i]或者取piles[j],其中的较大者就是我们要的选择方式:

dp[i][j] = max(piles[i] - dp[i + 1][j], piles[j] - dp[i][j - 1])

附上完整代码:

class Solution {
public:
    bool stoneGame(vector<int>& p) {
        int n = p.size();
        vector<vector<int>> dp(n, vector<int>(n, 0));
        for (int i = 0; i < n; i++) dp[i][i] = p[i];
        for (int d = 1; d < n; d++)
            for (int i = 0; i < n - d; i++)
                dp[i][i + d] = max(p[i] - dp[i + 1][i + d], p[i + d] - dp[i][i + d - 1]);
        return dp[0][n - 1] > 0;
    }
};

算法的时间复杂度为O(n^3)

但是,其实这个题我们可以从另一个角度来看:
我们可以把整个序列根据位置分成偶数位置的石头堆(0,2,4……)和奇数位置的石头堆(1,3,5……),由于石头的总数为奇数,那么这两堆中必然有1堆大,有1堆小。由于Alex总是先选,简单推理可知,那么他永远可以自由地选择自己拿所有的奇数堆还是所有的偶数堆,那么Alex实际上已经立于不败之地。综上,整个算法的代码其实只需一行!

return true;

当然,如果堆的总数不是奇数,那么你还是需要使用DP来求解。

附上LeetCode链接:https://leetcode.com/problems/stone-game/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值