码迷,mamicode.com
首页 > 编程语言 > 详细

【算法功底】LeetCode 292 Nim Game

时间:2017-03-24 23:07:52      阅读:210      评论:0      收藏:0      [点我收藏+]

标签:friend   min   桌子   bool   递推   example   正整数   函数   ever   

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.

 

题目:

你和你的好基友在玩一个叫Nim的游戏:桌子上有一堆小石子,你或你基友轮流从中拿出1到3颗小石子。能拿完最后剩下的所有小石子的人获胜。你先开始拿。

假设:你和你基友都是IQ非常高的人,而且都是玩这个游戏的老手(深谙玩这个游戏的套路)。

你能否写个函数,用来计算对给定数目的小石子,你是否能赢下比赛。

eg:如果有4个小石子,你肯定会输的,因为不管你拿走1个、2个还是3个,最后剩下的小石子都会被你好基友拿完。

 

分析:如果轮到你拿的时候,剩下4个小石子,你就悲剧了。

    同理,如果你拿的时候还剩下8个小石子,不管你选择拿1个、2个还是3个,你朋友都能让你下次拿的时候剩下4个。

    递推地:假设在轮到你你拿的时候还剩4*n个小石子,不管你选择拿1个、2个还是3个,你朋友都能让你下次拿的时候还剩4*(n-1)个;

    也就是,你朋友可以让你每次拿之前,都剩4n个小石子;(n为大于等于1的正整数);这样递推下去,最后你就输了。

 

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

 

    

 

【算法功底】LeetCode 292 Nim Game

标签:friend   min   桌子   bool   递推   example   正整数   函数   ever   

原文地址:http://www.cnblogs.com/HITSZ/p/6613692.html

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