【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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM