Coins in a Line

题目

原题链接: 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

public boolean firstWillWin(int n) { if(n <= 0) { return false; } if(n == 1) { return true; } boolean[] dp = new boolean[n]; dp[0] = true; dp[1] = true; for(int i = 2; i < n; i++) { dp[i] = !dp[i-1] || !dp[i-2]; } return dp[n-1]; }



显然复杂度是O(n)


results matching ""

    No results matching ""