LeetCode -- Nim Game
2015-10-28 21:39
295 查看
(许久没做LeetCode了呢。最近有些心神不宁,没什么动力,不知道自己每天在干什么,想不通自己生存的意义,不知道自己真正喜欢的是什么。总之,平时不想的一些问题,一旦想到心情就会很low。)
Question:
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.
Analysis:
问题描述:你与你的朋友玩Nim Game:在桌子上有一堆石头,每次可以从中取1-3块石头。规则是取走桌上最后一个石头的人获胜。你有优先拿石头的权利。你们两个都很聪明而且有玩游戏的最佳解决方案。给出一堆具有固定数目的石头,写一个函数判断你是否是此次游戏的赢家。
例如,如果桌上有4块石头,那你不可能赢得游戏:不论你首先拿1/2/3块,最后一块石头总是会被你的朋友拿走。
思路:我们已经知道当桌上有4块石头时,不论怎样你都会输掉游戏。那么当桌上有8块(4的倍数时),总能分成n*4次,每次不论取多少块石头,朋友总能使此次变成以4为一个回合,因此会输掉game。
Answer:
Question:
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.
Analysis:
问题描述:你与你的朋友玩Nim Game:在桌子上有一堆石头,每次可以从中取1-3块石头。规则是取走桌上最后一个石头的人获胜。你有优先拿石头的权利。你们两个都很聪明而且有玩游戏的最佳解决方案。给出一堆具有固定数目的石头,写一个函数判断你是否是此次游戏的赢家。
例如,如果桌上有4块石头,那你不可能赢得游戏:不论你首先拿1/2/3块,最后一块石头总是会被你的朋友拿走。
思路:我们已经知道当桌上有4块石头时,不论怎样你都会输掉游戏。那么当桌上有8块(4的倍数时),总能分成n*4次,每次不论取多少块石头,朋友总能使此次变成以4为一个回合,因此会输掉game。
Answer:
public class Solution { public boolean canWinNim(int n) { if(n % 4 == 0) return false; return true; } }
相关文章推荐
- Jquery Ajax
- Jquery 方法大全
- LeetCode Valid Anagram (简单题)
- HTTP 错误 403.14 - Forbidden Web 服务器被配置为不列出此目录的内容。
- 数据库命名规则
- Linux指令_文件处理工具sed
- Spark修炼之道(高级篇)——Spark源码阅读:第七节 resourceOffers方法与launchTasks方法解析
- java Io 全解
- 【LeetCode】Serialize and Deserialize Binary Tree 解题报告
- 05-树9 Huffman Codes
- fragment 的repalce方法和hide和show
- hdu 4633 Who's Aunt Zhang(polya)
- cxf 创建动态webService
- 将中缀表达式转化为后缀表达式
- Mondrian 使用教程
- 约瑟夫环问题之选猴王
- 约瑟夫环问题之选猴王
- Android学习笔记之Activity Intent 数据传输之回传结果
- C-结构
- c# 语言基础