【leetcode】1025. Divisor Game

题目如下:

Alice and Bob take turns playing a game, with Alice starting first.

Initially, there is a number N on the chalkboard.  On each player's turn, that player makes a move consisting of:

  • Choosing any x with 0 < x < N and N % x == 0.
  • Replacing the number N on the chalkboard with N - x.

Also, if a player cannot make a move, they lose the game.

Return True if and only if Alice wins the game, assuming both players play optimally.

 

Example 1:

Input: 2
Output: true
Explanation: Alice chooses 1, and Bob has no more moves.

Example 2:

Input: 3
Output: false
Explanation: Alice chooses 1, Bob chooses 1, and Alice has no more moves.

 

Note:

  1. 1 <= N <= 1000

解题思路:假设当前操作是Bob选择,我们可以定义一个集合dic = {},里面存储的元素Bob必输的局面。例如当前N=1,那么Bob无法做任何移动,是必输的场面,记dic[1] = 1。那么对于Alice来说,在轮到自己操作的时候,只有选择一个x,使得N-x在这个必输的集合dic里面,这样就是必胜的策略。因此对于任意一个N,只要存在 N%x == 0 并且N-x in dic,那么这个N对于Alice来说就是必胜的。只要计算一遍1~1000所有的值,把必输的N存入dic中,最后判断Input是否在dic中即可得到结果。

代码如下:

class Solution(object):
    dic = {1:1}
    def init(self):
        for i in range(2,1000+1):
            flag = False
            for j in range(1,i):
                if i % j == 0 and i - j in self.dic:
                    flag = True
                    break
            if flag == False:
                self.dic[i] = 1

    def divisorGame(self, N):
        """
        :type N: int
        :rtype: bool
        """
        if len(self.dic) == 1:
            self.init()
        return N not in self.dic

 

posted @ 2019-04-21 10:21  seyjs  阅读(1070)  评论(0编辑  收藏  举报