Coins in a Line

Posted warmland

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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的主要内容,如果未能解决你的问题,请参考以下文章

Coins in a Line

Coins in a Line II

Coins in a Line III

LeetCode Coins in a Line

Coins in a Line II

[LintCode] Coins in a Line II