一.解法
https://leetcode-cn.com/problems/nim-game/
要點(diǎn):數(shù)學(xué),動(dòng)態(tài)規(guī)劃
一開始想到用動(dòng)態(tài)規(guī)劃做,見java代碼,思路是判斷自己拿了1-3個(gè)后再之前的三個(gè)狀態(tài),但是數(shù)字大了會(huì)超時(shí),LeetCode過不了。
規(guī)律以及數(shù)學(xué)告訴我們,每次摸1-3個(gè)只要保證對(duì)手摸的時(shí)候是4的倍數(shù)就能贏,所以n一開始不為4的倍數(shù)先手必贏。
二.Python實(shí)現(xiàn)
class Solution:
def canWinNim(self, n: int) -> bool:
return n%4!=0;
三.C++實(shí)現(xiàn)
class Solution {
public:
bool canWinNim(int n) {
return n%4!=0;
}
};
四.java實(shí)現(xiàn)
class Solution {
public boolean canWinNim(int n) {
if(n <= 3) return true;
if(!canWinNim(n - 1) || !canWinNim(n - 2) || !canWinNim(n - 3)) return true;
return false;
}
}
//以上方法會(huì)超時(shí)
class Solution {
public boolean canWinNim(int n) {
return n%4!=0;
}
}
//數(shù)學(xué)方法