代码改变世界

[LintCode] 394. Coins in a Line_ Medium tag:Dynamic Programming_博弈

2018-07-25 23:16  Johnson_强生仔仔  阅读(319)  评论(0编辑  收藏  举报

Description

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

Challenge

O(n) time and O(1) memory

 

这个题目是属于经典的博弈类Dynamic Programming 的入门题目, 为了便于思考, 我们只考虑一个选手的status, 例如我们只考虑first player的状态, 然后 A[i] 表明到first player下时还

剩下i个coins, 找到动态关系式:    A[i] = (A[i-2] and A[i-3]) or (A[i-3] and A[i-4])    第一个是first player只选一个, 第二个是first player选2个之后由second player选了之后的到first player

下了的状态, 所以将second player的状态放入到了first player的状态当中. 此时需要注意的是初始化dp数组时, 要初始化0, 1,2, 3, 4

 

1. Constraints

1) n >= 0 integer

 

2. ideas

DP    T: O(n)   S; O(1)   optimal by rolling array

 

3. code

1) S: O(n)

class Solution:
    def coinsInLine(self, n):
        ans = [True]*5
        ans[0] = ans[3] = False
        if n < 5: return ans[n]
        ans = ans + [None]*(n-4)
        for i in range(5, n+1):
            ans[i] = (ans[i-2] and ans[i-3]) or (ans[i-3] and ans[i-4])
        return ans[n]

 

2) S: O(1)

 

class Solution:
    def coinsInLine(self, n):
        ans = [True] *5
        ans[0] = ans[3] = False
        if n < 5: return ans[n]
        for i in range(5, n + 1):
            ans[i%5] = (ans[i%5-2] and ans[i%5-3]) or (ans[i%5-3] and ans[i%5-4])
        return ans[n%5]

 

3) 666

class Solution:
    def coinsInLine(self, n):
        return not (n%3 == 0)

 

4. Test cases

1) 0-6