【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
相關文章
相關標籤/搜索