美文网首页
Coins in a Line

Coins in a Line

作者: Star_C | 来源:发表于2018-04-04 23:11 被阅读0次

Question

from lintcode

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.

Idea

It's a bit tricky to define the DP function. The goal is to see if the first player will win. In another word, we want to know if the last coin can be taken by the first player. If the last coin can be picked by the first player, he must not have taken the previous two elements, in which case the second player will win.

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) {
        if (n == 0) return false;
        if (n == 1 || n == 2) return true;

        boolean[] canFisrtPlayerTake = new boolean[n + 1];
        canFisrtPlayerTake[0] = false;
        canFisrtPlayerTake[1] = true;
        canFisrtPlayerTake[2] = true;
        for (int i = 3; i <= n; i++)
            canFisrtPlayerTake[i] = !canFisrtPlayerTake[i - 1] || !canFisrtPlayerTake[i - 2];

        return canFisrtPlayerTake[n];
    }
}

相关文章

网友评论

      本文标题:Coins in a Line

      本文链接:https://www.haomeiwen.com/subject/pcolhftx.html