292. Nim Game

雨点打透心脏的1/2处 2022-06-09 03:55 274阅读 0赞
  1. /*
  2. 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.
  3. 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.
  4. 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.
  5. */
  6. /*
  7. 因为只能移动1、2、3块石头,所以只要对手最后拿的时候剩下4块石头,那无论他拿走几块石头,我都可以全部拿完,而之前每次拿石头,不管对手拿几个,我都以凑够4个为目标拿。所以在我第一个拿石头的前提下,只要总数除以4有余数,我第一次拿余数即可保证对手最后一次拿之前只剩下4颗石头。
  8. */
  9. //3ms 0%
  10. bool canWinNim(int n) {
  11. return n%4!=0;
  12. }

发表评论

表情:
评论列表 (有 0 条评论,274人围观)

还没有评论,来说两句吧...

相关阅读

    相关 LeetCode 292 Nim GameNim游戏)

    你和你的朋友,两个人一起玩 Nim游戏:桌子上有一堆石头,每次你们轮流拿掉 1 - 3 块石头。 拿掉最后一块石头的人就是获胜者。你作为先手。 你们是聪明人,每一步都是最优解