LeetCode486. Predict the Winner题解

1. 题目描述

Given an array of scores that are non-negative integers. Player 1 picks one of the numbers from either end of the array followed by the player 2 and then player 1 and so on. Each time a player picks a number, that number will not be available for the next player. This continues until all the scores have been chosen. The player with the maximum score wins. Given an array of scores, predict whether player 1 is the winner. You can assume each player plays to maximize his score.
【翻译过来】:给了一个数组,每次两个人依次选择拿走数组的头元素或者尾元素,当数组被拿空的时候计算每个人拿走的元素之和,之和大的一方获胜。题目要求Player1首先开始,给定数组和此规则之后,需要预测player1能否获胜。

2. 样例

Input: [1, 5, 2]
Output: False
Explanation: Initially, player 1 can choose between 1 and 2. If he chooses 2 (or 1), then player 2 can choose from 1 (or 2) and 5. If player 2 chooses 5, then player 1 will be left with 1 (or 2). So, final score of player 1 is 1 + 2 = 3, and player 2 is 5. Hence, player 1 will never be the winner and you need to return False.


Input: [1, 5, 233, 7]
Output: True
Explanation: Player 1 first chooses 1. Then player 2 have to choose between 5 and 7. No matter which number player 2 choose, player 1 can choose 233. Finally, player 1 has more score (234) than player 2 (12), so you need to return True representing player1 can win.

3. 分析

其实,直到现在为止,我对题目仍有异议:因为Player1能否获胜,很大程度上是受到了Player2走棋的影响,题目并没有规定清楚Player2是如何操作的,那么我们得到的结果我不认为有什么意义。
换句话说,如果题目的要求是“预测Player1能否获胜”,那么问题就容易多了,我们只要找到一种走法,能够Player1获胜即可,显然题目并不是这个意思。
根据我的猜测,题目的意思是:有没有一种策略能够让Player1获胜
看了讨论区大佬们的思路之后,我决定用了DP(动态规划)的思路,我们对变量进行如下的规定:

  • score[i][j]:代表了Player1在区间[i, j]内可以获得的最大值;
  • prefixSum[j]:代表了在区间[i,j]内所有nums的score之和;
  • nums[lhs] + prefixSum[rhs+1] - prefixSum[lhs+1] - score[lhs+1][rhs]:代表选择了左端点的值;
  • nums[rhs] + prefixSum[rhs] - prefixSum[lhs] - score[lhs][rhs-1]:代表选择了右端点的值;
  • len:代表了当前区间长度;
  • lhs:区间的左端点;
  • rhs:区间的右端点;

其实我们最后需要比较的就是:score[0][nums.size()-1]是否大于等于prefixSum[nums.size()-1]的一半,即Player1的score是否超过整个区间总score的一半。

接下来,我们将区间的长度从1开始,左边端点每一次从0开始进行遍历,模拟Player1的每一次选择,每一次都选择左右两个端点里面数值大的那一个。
这里写图片描述

4. 源码

/*
 * main.cpp
 *
 *  Created on: 2017年5月24日
 *      Author: liboyang
 */
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;

bool PredictTheWinner(vector<int>& nums);
int main() {
    vector<int> test;
    test.push_back(1);
    test.push_back(5);
    //test.push_back(2);
    test.push_back(233);
    test.push_back(7);
    bool result = PredictTheWinner(test);
    if (result == true) {
        cout << "true" << endl;
    }
    else {
        cout << "false" << endl;
    }
    return 0;
}

bool PredictTheWinner(vector<int>& nums) {
        vector<vector<int>> score(nums.size(), vector<int>(nums.size()));
        vector<int> prefixSum(nums.size()+1);
        prefixSum[0] = 0;
        for (int i=0; i<nums.size(); i++) {
            prefixSum[i+1] = prefixSum[i] + nums[i];
        }

        for (int len=1; len<=nums.size(); len++) {
            for (int lhs=0; lhs+len-1<nums.size(); lhs++) {
                int rhs = lhs + len - 1;
                if (lhs == rhs) {
                    score[lhs][rhs] = nums[lhs];
                } else if (lhs == rhs-1) {
                    score[lhs][rhs] = max(nums[lhs], nums[rhs]);
                } else {
                    int pickLeft = nums[lhs] + prefixSum[rhs+1] - prefixSum[lhs+1] - score[lhs+1][rhs];
                    int pickRight = nums[rhs] + prefixSum[rhs] - prefixSum[lhs] - score[lhs][rhs-1];
                    score[lhs][rhs] = max(pickLeft, pickRight);
                }
            }
        }

        return score[0][nums.size()-1] >= prefixSum.back()/2 + prefixSum.back()%2;
    }

5. 心得

这道题的解法是看了大佬们的算法才想到的方案,我原先的方案很简单:完全模拟游戏规则,设计一个bool 变量用来记录当前的游戏玩家,如下所示:
【错误的代码】:

bool PredictTheWinner(vector<int>& nums) {
    int maxValue = 0;
    int scorePlayer = 0;
    for (int i = 0; i < (int)nums.size(); i++) {
        maxValue += nums[i];
    }
    int left = 0;
    int right = nums.size() - 1;
    bool player1 = true;
    while(left <= right) {
        if (left < right) {
            if (player1 == true) {
                scorePlayer += max(nums[left], nums[right]);
                if (nums[left] >= nums[right]) {
                    left++;
                }
                else {
                    right--;
                }
            }
            else {
                if (nums[left] >= nums[right]) {
                    right--;
                }
                else {
                    left++;
                }
            }
            player1 = !player1;
        }
        else if (left == right) {
            if (player1 == true) {
                scorePlayer += nums[left];
            }
            break;
        }
        else {
            return false;
        }
    }

    if (scorePlayer >= maxValue/2) {

        return true;
    }
    return false;
}

原因:根据错误的样例我大概也知道是将Player2的做法设计的过于愚蠢,无法通过某些样例,例如:

[1, 5, 2]
player1: 1, [5, 2]
player2: 2, [5]
player1: 5, [0]
player1: 1+5 = 6 > 2, return true
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值