【leetcode】1025. Divisor Game

题目以下:spa

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

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

  • 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.ci

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

 

Example 1:it

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

Example 2:io

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

 

Note:class

  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中便可获得结果。object

代码以下:im

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
相关文章
相关标签/搜索