首页 > 代码库 > Coins in a Line

Coins in a Line

ref: http://www.lintcode.com/en/problem/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?

 

Example

n = 1, return true.

n = 2, return true.

n = 3, return false.

n = 4, return true.

n = 5, return true.

 


 

思路是从后往前做,如果第i步一个人会赢,那么就说明,另外一个人不能在[i-1]和[i-2]里面都赢。

所以状态转移方程是dp[i] = !dp[i-1] || !dp[i-2]

因为后面的状态需要用前面的状态,所以从前往后走

初始化是dp[0] = true; dp[1] = true

 1     public boolean firstWillWin(int n) {
 2         if(n <= 0) {
 3             return false;
 4         }
 5         if(n == 1) {
 6             return true;
 7         }
 8         boolean[] dp = new boolean[n];
 9         dp[0] = true;
10         dp[1] = true;
11         for(int i = 2; i < n; i++) {
12             dp[i] = !dp[i-1] || !dp[i-2];
13         }
14         return dp[n-1];
15     }

显然复杂度是O(n)

Coins in a Line