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];
}
}