码迷,mamicode.com
首页 > 其他好文 > 详细

292. Nim Game

时间:2017-02-01 00:48:48      阅读:207      评论:0      收藏:0      [点我收藏+]

标签:div   style   str   --   amp   color   friend   boolean   follow   

题目

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.

Hint:

  1. If there are 5 stones in the heap, could you figure out a way to remove the stones such that you will always be the winner?

分析

每次移走1~3个石头,我先来,谁移走最后一块石头谁赢,根据石头总数求出我是否会赢

若n=1、2、3;赢

若n=4,我1--敌3,我2--敌2,我3--敌1;输

若n=5,我1--敌1--我3,我1--敌2--我2,我1--敌3--我1;赢

若n=6,我2--敌1--我3,我2--敌2--我2,我2--敌3--我1;赢

若n=7,我3--敌1--我3,我3--敌2--我2,我3--敌3--我1;赢

若n=8,我1--敌3--剩4,我2--敌2--剩4,我3--敌1--剩4;输

……

若n为4的倍数,输;否则,赢。


解答

解法1:(我)(0ms)

1 public class Solution {
2     public boolean canWinNim(int n) {
3         return n % 4 != 0;
4     }
5 }

292. Nim Game

标签:div   style   str   --   amp   color   friend   boolean   follow   

原文地址:http://www.cnblogs.com/xuehaoyue/p/6359678.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!