[leetcode #1510] Stone Game IV

Seongyeol Shin·2022년 1월 22일
0

leetcode

목록 보기
138/196
post-thumbnail

Problem

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

Initially, there are n stones in a pile. On each player's turn, that player makes a move consisting of removing any non-zero square number of stones in the pile.

Also, if a player cannot make a move, he/she loses the game.

Given a positive integer n, return true if and only if Alice wins the game otherwise return false, assuming both players play optimally.

Example 1:

Input: n = 1
Output: true
Explanation: Alice can remove 1 stone winning the game because Bob doesn't have any moves.

Example 2:

Input: n = 2
Output: false
Explanation: Alice can only remove 1 stone, after that Bob removes the last one winning the game (2 -> 1 -> 0).

Example 3:

Input: n = 4
Output: true
Explanation: n is already a perfect square, Alice can win with one move, removing 4 stones (4 -> 0).

Constraints:

・ 1 <= n <= 10⁵

Idea

오늘도 풀지 못 했다 🥲 생각을 깊게 하는 습관을 다시 한 번 들여야겠다.

Alice와 Bob이 제곱수만큼 돌을 가지고 갈 수 있으며, 마지막에 돌을 가지고 가는 사람이 이기는 게임이다. 두 사람 모두 최적으로 게임을 한다고 가정할 때 주어진 돌의 개수 n에서 Alice가 이기는 지 여부를 리턴하면 된다.

풀이를 보면 의외로 간단하다. dp를 어떻게 계산하는지가 관건인데, dp를 Alcie가 이기는지 여부로 판단하면 된다.

0~n까지의 수에 대해 계산하며, dp값이 true라면 계산하지 않아도 된다. (Alice가 이기므로 여기에 제곱수를 더해봤자 Alice가 이기는 경우는 없다.) 다만 dp가 false가 나왔을 때는 Bob이 이기는 경우므로 이 때 제곱수를 더하면 Alice가 이긴다는 뜻이 된다. 따라서 dp가 false일 때만 제곱수를 더 한 경우 전부를 true로 계산한다.

마지막에 dp의 index n값을 리턴하면 된다.

Solution

class Solution {
    public boolean winnerSquareGame(int n) {
        boolean[] dp = new boolean[n+1];

        for (int i=0; i < n; i++) {
            if (dp[i]) {
                continue;
            }

            for (int k=1; i + k * k <= n ; k++) {
                dp[i + k * k] = true;
            }
        }

        return dp[n];
    }
}

Reference

https://leetcode.com/problems/stone-game-iv/

profile
서버개발자 토모입니다

0개의 댓글