Algorithm

[LeetCode] #1025. Divisor Game - Python

inistory 2019. 11. 6. 01:21

1. ๋ฌธ์ œ

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

2. ์†Œ์Šค์ฝ”๋“œ

class Solution(object): 
    def divisorGame(self, N): 
        cnt = 0 
        while N!=1: 
            x = [] 
            for i in range(1,N): 
                if N%i ==0: 
                    x.append(i) 
            N = N -x[0] 
            cnt +=1 
        if cnt%2 ==0: 
            return False 
        else: 
            return True

 


3. ์†Œ์Šค์ฝ”๋“œ ์„ค๋ช…

Bob๊ณผ Alice๊ฐ€ ์น ํŒ์— ์ ์–ด๊ฐ€๋ฉฐ DivisorGame์„ ํ•œ๋‹ค.

N์ด๋ผ๋Š” ์ˆ˜๊ฐ€ ์ฃผ์–ด์ง€๋Š”๋ฐ, ์šฐ๋ฆฌ๋Š” 0<x<N์ด๋ฉด์„œ N%x ==0์ธ x ๋ฅผ ์ฐพ์•„์•ผํ•œ๋‹ค.

์—ฌ๊ธฐ์„œ x์— ํ•ด๋‹นํ•˜๋Š” ์ˆ˜๋Š” N์˜ ์•ฝ์ˆ˜๋“ค ์ค‘, N๋ฅผ ์ œ์™ธํ•œ ๊ฒƒ์ด๋ผ๊ณ  ์ดํ•ดํ–ˆ๋‹ค.

๋”ฐ๋ผ์„œ for๋ฌธ์„ 1๋ถ€ํ„ฐ N ์ „๊นŒ์ง€ ๋Œ๋ฉด์„œ, ๋‚˜๋ˆ„์—ˆ์„ ๋•Œ 0์ด ๋˜๋Š” ์ˆ˜๋“ค์„ x ๋ฆฌ์ŠคํŠธ์— ๋„ฃ๋Š”๋‹ค.

์ด ์ค‘์—์„œ player๊ฐ€ ์ฒซ๋ฒˆ์งธ x๋ฅผ ์„ ํƒํ•˜๊ณ , ๊ทธ ์„ ํƒํ•œ x๋ฅผ N์—์„œ ๋บ€๋‹ค.

๊ทธ ์ˆ˜๊ฐ€ ๋‹ค์‹œ N์ด ๋˜๋Š” ๊ฒƒ์ด๋ฏ€๋กœ N = N -x[0] ๋ผ๊ณ  ์จ์ค€๋‹ค.

cnt๋กœ๋Š” ์น ํŒ์— ์ ๋Š” ํšŸ์ˆ˜๋ฅผ ์นด์šดํŠธํ•  ๊ฒƒ์ธ๋ฐ, ์ƒˆ๋กœ์šด N์ด ์—…๋ฐ์ดํŠธ ๋  ๋•Œ๋งˆ๋‹ค count ํ•ด์ฃผ์–ด์•ผํ•˜๋ฏ€๋กœ ๊ทธ ๋ฐ‘์— +1์—ฐ์‚ฐ์ž๋ฅผ ์จ์ฃผ์—ˆ๋‹ค.

Alice๊ฐ€ ๋จผ์ € ๊ฒŒ์ž„์„ ์‹œ์ž‘ํ•˜๋Š” ๊ฒƒ์ด๋ฏ€๋กœ, cnt๊ฐ’์ด ์ง์ˆ˜์ผ ๋•Œ๋Š” false(ํŒจ๋ฐฐ)๋ฅผ, cnt๊ฐ’์ด ํ™€์ˆ˜ ์ผ ๋•Œ๋Š” true(์Šน๋ฆฌ)๋ฅผ ๋ฐ˜ํ™˜ํ•œ๋‹ค.