lintcode-medium-Coins in a Line

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?

 

n = 1, return true.

n = 2, return true.

n = 3, return false.

n = 4, return true.

n = 5, return true.

 

 

这道题的思路:

玩家可以一次拿1个或者2个硬币,如果总硬币数不能被3整除,或者说总数为3n+1 或者3n+2,先拿的人可以拿1个或者2个,使得总数剩下3n,再根据后拿的人拿的个数,使得剩下的硬币数为3n,于是先拿的人总是能赢。

如果总数为3n,则后拿的人肯定可以赢

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

 

posted @ 2016-03-15 13:33  哥布林工程师  阅读(130)  评论(0编辑  收藏  举报