Description
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
, returntrue
.
n =2
, returntrue
.
n =3
, returnfalse
.
n =4
, returntrue
.
n =5
, returntrue
.
Solution
第一个拿的人胜利意味着这个人拿一个或者两个会使 下一个拿的人输。故状态方程是win[i] = !win[i - 1] || !win[i - 2]
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
if (n <= 0) {
return false;
}
if (n == 1) {
return true;
}
boolean[] win = new boolean[n + 1];
win[1] = true;
win[2] = true;
for (int i = 2; i <= n; i++) {
win[i] = !win[i - 1] || !win[i - 2];
}
return win[n];
}
}