#395 Coins in a Line II

题目描述:

There are n coins with different value in a line. Two players take turns to take one or two coins from left side until there are no more coins left. The player who take the coins with the most value wins.

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

Example

Given values array A = [1,2,2], return true.

Given A = [1,2,4], return false.

题目思路:

这题的思路和#394类似:自己有两种选择:拿1或者拿2.但是对手的选择(1或者2)都是必须让自己拿的最少的。自己拿1的时候:对手的选择是dp[i - 3]和dp[i-2]里取最小;自己拿2的时候,对手在dp[i - 4]和 dp[i - 3]取最小。但是自己可以在拿1和拿2中选个最大值。

这题比较坑爹的是要注意初始化啊初始化。必须要从array的尾巴开始初始化和计算,因为从头看是有uncertainty的,我们是不知道到底应该怎么取的。

Mycode(AC = 11ms):

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 &values) {
        // write your code here
        if (values.size() == 0) {
            return false;
        }
        else if (values.size() <= 2) {
            return true;
        }
        else if (values.size() == 3) {
            return values[0] + values[1] > values[2];
        }
        else {
            int n = values.size();
            vector dp(n + 1, 0);
            
            // must initial from tail, because
            // how to pick from head is uncertain
            dp[1] = values[n - 1];
            dp[2] = values[n - 1] + values[n - 2];
            dp[3] = values[n - 3] + values[n - 2];
            
            int total = values[0] + values[1] + values[2];
            
            for (int i = 4; i <= values.size(); i++) {
                total += values[i - 1];
                dp[i] = max(min(dp[i - 4], dp[i - 3]) + values[n - i + 1] + values[n - i], // if player1 pick 2 coins
                            min(dp[i - 3], dp[i - 2]) + values[n - i]); // if player 1 pick 1 coin
            }
            
            return dp[n] > total - dp[n];
        }
    }
};

你可能感兴趣的:(lintcode)