Coins in a Line

here 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.

Tags 

 
思路:1.   本题属于博弈论问题,可以采用动态规划的方法解决。
     2.  对于博弈论问题,游戏中的玩家都是AlphaGo级别即总数选择最优的策略。
   3.  题目问的是先手是否必胜。先手必胜状态 ( = 后手必败状态,又叫N-position)(这里的状态其实就是局面) 先手必败状态 ( = 后手必胜状态,又叫P-position)。注意
    先手、后手状态是对于局面来说的,一个人在局面A时可能是先手,在局面B时可能是后手。先手必胜当且仅当它的子状态存在一个先手必败状态,而先手必败状态则是当且仅当它的子状                 态都是先手必胜状态。
    4. 令DP[n] 表示存在n枚硬币时,先手是否必胜。 则DP[n] = !(DP[n - 1] && DP[n - 2])。DP[0] = false. DP[1] = DP[2] = true
 1 public class Solution {
 2     /**
 3      * @param n: an integer
 4      * @return: a boolean which equals to true if the first player will win
 5      */
 6     public boolean firstWillWin(int n) {
 7         // write your code here
 8         // dp[n] 代表有n枚硬币的条件下,先手是否获胜。
 9         // 获胜的条件是 存在一种情况 即 dp[n - 1] 或 dp[n - 2] 为false. 即能找到一种方案使对手不能获胜。 
10         if (n == 0) {
11             return false;
12         }
13         boolean[] dp = new boolean[n + 1];
14         dp[0] = false;
15         dp[1] = true;
16         for (int i = 2; i <= n; i++) {
17             dp[i] = !dp[i - 1] || !dp[i - 2];
18         }
19         return dp[n];
20     }
21 }

 

posted @ 2017-09-11 10:31  YuriFLAG  阅读(181)  评论(0)    收藏  举报