LeetCode ---- Nim Game (Java/Lua 实现)

来源:互联网 发布:隔音窗户 知乎 编辑:程序博客网 时间:2024/05/22 13: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.

大概翻译下:
桌上有一堆石头,你和你朋友玩游戏,规则如下,你和你的朋友(另一个人,总共 2 人)轮流每次拿走 1-3 块石头,谁拿走最后的石头就是胜者。你将第一个开始拿走石头。
设计一个程序分析总共多少块石头的情况下你能赢得比赛。
比如,如果有 4 块石头,那么你永远不可能赢得比赛,因为不管你是拿 1 块、2块,还是3块,最后的时候都是你朋友拿走的。

提示:如果堆中有 5 个石头,怎么样取你才能获胜?

5 块的时候,你先拿 1 块,然后剩下 4 块,根据题目中的样例,你会发现在剩 4 块时候,谁先拿谁就输了。

当n∈[1,3]时,先手必胜。

当n == 4时,无论先手第一轮如何选取,下一轮都会转化为n∈[1,3]的情形,此时先手必负。

当n∈[5,7]时,先手必胜,先手分别通过取走[1,3]颗石头,可将状态转化为n == 4时的情形,此时后手必负。

当n == 8时,无论先手第一轮如何选取,下一轮都会转化为n∈[5,7]的情形,此时先手必负。

归纳分析,在石头为 4 的倍数时,先手就会失败。


Java 语言实现:

public static boolean canWinNim(int n) {    if (n % 4 == 0)        return false;    return true;}


Lua 语言实现:
 function canWinNim(nums)     assert(type(nums) == "number", "arguments num is not a number")     return nums % 4 ~= 0 end print(canWinNim(1))



注意到 lua 语法:
  • 非是 ~,而不是 Java 中的 !
  • Lua 动态类型语言,数值才是有类型的,变量无类型(Java 传入参数 int n,而 lua 直接 nums)

1 0
原创粉丝点击