292. Nim Game My Submissions Question

292. Nim Game My Submissions Question

Total Accepted: 30656 Total Submissions: 60993 Difficulty: Easy
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.

是个dp问题,也和博弈论相关的一个问题。做了很久没有找到思路,discuss看到答案 n%4!=0 .基本都是根据规律得出的答案。总感觉这种做法不好。没有逻辑可言,也仅仅只能做出这道题,如果换种形式难道不成又去找规律。。这肯定不行的。

根据问题 得知 一个人每次只能最多只能够取3块石子。如果只剩下4块石子,那么剩下的4块石子,谁先取肯定就输了。

假设石子的总数为 N. 那么 总有
N = 4*x+y
即石子的总数 能够用4的倍数来表示.

那么 就有如下几种情况:

1: y=0;
这种情况谁先取,谁就输了。
因为 一个人最多只能够取3个石子,
假设A取 x1 个石子块,
B取x2个石子块,
那么地个人总能够使得 :
x1+x2=4.
第一轮之后剩余的石子数量为:
N=4x-4.
还是4的倍数,重复上面的操作知道剩余的石子总数:
N=4。
明显,A输了。
也即是 这种情况 谁先取,谁就输了。

2: y!=0

还是A先取,A第一步取y块石子,那么剩余的石子数量:
N=4x-y=4x,
这时轮到B取了,发先问题又回到了第一种情况,很明显
安装情况1的策略,B 肯定输了。

那么这题的答案
public class Solution {
public boolean canWinNim(int n) {
return n%4!=0;

}

}

不难理解了。

这到题目是Nim游戏 的一个版本。看了想关的博客,发现了
这篇介绍的比较易理解,其它的介绍看了许久都没看出个所以然。

http://wenku.baidu.com/view/8cc03974a417866fb84a8eeb.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值