LeetCode 292:Nim Game(尼姆游戏)

原创 2017年05月26日 15:51:48

You are playing the following Nim Game with your friend: There is a heap of stones on the table, each time one of you take turns to remove 1 to 3 stones. The one who removes the last stone will be the winner. You will take the first turn to remove the stones.

Both of you are very clever and have optimal strategies for the game. Write a function to determine whether you can win the game given the number of stones in the heap.

For example, if there are 4 stones in the heap, then you will never win the game: no matter 1, 2, or 3 stones you remove, the last stone will always be removed by your friend.

思路:

这其实是一个脑筋急转弯题,可以倒着想,因为每个人都不可能一次拿走4个石子,所以如果剩下4个石子,谁先拿谁输。所以如果想自己赢,就需要在倒数第3局的时候,自己拿走石子后保证剩下4个石子,这样小伙伴不管拿1,2或3个石子,都能保证自己拿走最后一个石子。同理,要想自己最终赢得胜利,只需要保证倒数2n+1局的时候,自己拿走石子后保证剩下的石子数为4的倍数。因为自己第一个拿,所以只有石子总数不是4的倍数,这样自己拿走除以4后余数个石子,才能保证剩下的石子数是4的倍数,取得游戏的胜利。综上:若石子数是4的倍数,则输;否则,赢。

Code:

class Solution {
public:
    bool canWinNim(int n) {
        if (n%4!=0) return true;
        else return false;
    }
};


LeetCode(292) Nim Game

题目You are playing the following Nim Game with your friend: There is a heap of stones on the table, e...
  • fly_yr
  • fly_yr
  • 2015-11-27 15:58:30
  • 985

LeetCode 292 Nim Game(Nim游戏)

翻译你正在和你的朋友们玩下面这个Nim游戏:桌子上有一堆石头,每次你从中去掉1-3个。谁消除掉最后一个石头即为赢家。你在取出石头的第一轮。你们中的每一个人都有着聪明的头脑和绝佳的策略。写一个函数来确定...
  • NoMasp
  • NoMasp
  • 2015-12-23 20:24:58
  • 5754

LeetCode292——Nim Game(一行代码解决)

You are playing the following Nim Game with your friend: There is a heap of stones on the table, eac...
  • booirror
  • booirror
  • 2015-10-20 23:58:46
  • 8535

【LeetCode】292 Nim Games (java实现)

You are playing the following Nim Game with your friend: There is a heap of stones on the table, eac...
  • styshoo
  • styshoo
  • 2015-12-08 00:04:48
  • 538

减治法解决尼姆(Nim)游戏/拈游戏问题(JAVA)

尼姆游戏是一种两个人玩的回合制数学策略游戏。游戏者轮流从一堆棋子(一共有好几堆,一次只能从其中一堆拿。)(或者任何道具)中取走一个或者多个,最后不能再取的就是输家。当指定相应数量时,一堆这样的棋子称作...
  • qq_39630587
  • qq_39630587
  • 2018-02-03 21:38:35
  • 105

LeetCode 292.Nim Game 解题报告

LeetCode 292.Nim Game 解题报告
  • camellhf
  • camellhf
  • 2016-09-14 13:27:21
  • 370

[leetcode-292]Nim Game(java)

问题描述: You are playing the following Nim Game with your friend: There is a heap of stones on the tab...
  • zdavb
  • zdavb
  • 2015-10-13 14:46:56
  • 1235

尼姆博弈(n堆)

  • qq1169091731
  • qq1169091731
  • 2016-07-18 13:29:57
  • 222

[LeetCode 292] Nim Game

You are playing the following Nim Game with your friend: There is a heap of stones on the table, eac...
  • sbitswc
  • sbitswc
  • 2015-10-13 13:16:54
  • 3324

292. Nim Game [easy] (Python)

题目链接https://leetcode.com/problems/nim-game/题目原文 You are playing the following Nim Game with your f...
  • coder_orz
  • coder_orz
  • 2016-05-10 17:17:39
  • 1616
收藏助手
不良信息举报
您举报文章:LeetCode 292:Nim Game(尼姆游戏)
举报原因:
原因补充:

(最多只允许输入30个字)