码迷,mamicode.com
首页 > 其他好文 > 详细

Coins in a Line

时间:2016-11-05 07:43:06      阅读:256      评论:0      收藏:0      [点我收藏+]

标签:不能   line   who   style   []   layer   com   bsp   状态   

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

标签:不能   line   who   style   []   layer   com   bsp   状态   

原文地址:http://www.cnblogs.com/warmland/p/6032296.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!