Coins in a Line(Medium)

题目描述

There are n coins in a line. Two players take turns to take one or two coins from right side until there are no more coins left. The player who take the last coin wins. Could you please decide the first play will win or lose?

Example

n = 1, return true.
n = 2, return true.
n = 3, return false.
n = 4, return true.
n = 5, return true.

题目链接

解题思路

这题属于最简单的博弈模型(巴什博弈),即每次可以取1-k个。那么如果可以使得剩下的石子数量是 (1 + k) 的倍数,则先手必胜,否则先手必败。

参考代码

class Solution {
public:
    /**
     * @param n: an integer
     * @return: a boolean which equals to true if the first player will win
     */
     bool firstWillWin(int n) {
        // write your code here
        if (n % 3 == 0) return false;
        return true;
    }
};

results matching ""

    No results matching ""