1. 程式人生 > 其它 >【LeetCode】292. Nim Game Nim 遊戲(Easy)(JAVA)

【LeetCode】292. Nim Game Nim 遊戲(Easy)(JAVA)

技術標籤:Leetcode遊戲leetcodejava演算法資料結構

【LeetCode】292. Nim Game Nim 遊戲(Easy)(JAVA)

題目地址: https://leetcode.com/problems/nim-game/

題目描述:

You are playing the following Nim Game with your friend:

  • Initially, there is a heap of stones on the table.
  • You and your friend will alternate taking turns, and you go first.
  • On each turn, the person whose turn it is will remove 1 to 3 stones from the heap.
  • The one who removes the last stone is the winner.

Given n, the number of stones in the heap, return true if you can win the game assuming both you and your friend play optimally, otherwise return false.

Example 1:

Input: n = 4
Output: false
Explanation: These are the possible outcomes:
1. You remove 1 stone. Your friend removes 3 stones, including the last stone. Your friend wins.
2. You remove 2 stones. Your friend removes 2 stones, including the last stone. Your friend wins.
3. You remove 3 stones. Your friend removes the last stone. Your friend wins.
In all outcomes, your friend wins.

Example 2:

Input: n = 1
Output: true

Example 3:

Input: n = 2
Output: true

Constraints:

  • 1 <= n <= 2^31 - 1

題目大意

你和你的朋友,兩個人一起玩Nim 遊戲:

  • 桌子上有一堆石頭。
  • 你們輪流進行自己的回合,你作為先手。
  • 每一回合,輪到的人拿掉1 - 3 塊石頭。
  • 拿掉最後一塊石頭的人就是獲勝者。

假設你們每一步都是最優解。請編寫一個函式,來判斷你是否可以在給定石頭數量為 n 的情況下贏得遊戲。如果可以贏,返回 true;否則,返回 false 。

解題方法

  1. 因為每個人投的是 1-3 個石頭,而且最後一個投的能贏
  2. 如果 n 小於等於 3 個,肯定是第一個贏;如果 n 大於 3 個,第二個投了 k 個,第一個投 4 - k 個,最後剩下的就是 n % 4 個,等於 0 第二個贏,不等於 0 第一個贏
class Solution {
    public boolean canWinNim(int n) {
        return n % 4 != 0;
    }
}

執行耗時:0 ms,擊敗了100.00% 的Java使用者
記憶體消耗:35 MB,擊敗了90.11% 的Java使用者

歡迎關注我的公眾號,LeetCode 每日一題更新