Coins in a Line

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];
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容