1. 程式人生 > >演算法-Nim 遊戲-(拿石頭遊戲)

演算法-Nim 遊戲-(拿石頭遊戲)

題目: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.

題目的意思是,你和你的基友是兩個江洋大盜(只劫財不劫色那種,不知道是不是不行。。。),你倆面前有一堆鑽石,你倆要分鑽石,咋分呢,輪流拿唄,不過每次只能拿1到3個,不能多拿也不能不拿。規定誰拿到最後的鑽石誰就贏了(也是夠扯淡的,不看誰拿的多,而看誰拿到最後的鑽石。。。),從你開始先拿,而且你倆為了勝利,都絞盡腦汁,發揮250的智商,採取了最正確的策略。。。,現在讓寫個演算法,給定不同個數的鑽石,輸出最後的勝利者。。。我TM的就是個有職業操守的大盜,你TM的讓我寫演算法。。。

怕你和你基友不理解題目的意思,還特地舉個例子,例如現在有4個鑽石,你先拿,不管你拿幾個,最後都是你基友勝利。。。

分析:怎麼才能勝利呢,那就舉幾個栗子來看下唄(反正別的我也不會),鑽石小於4個時候,我直接拿走玩,臥槽,贏了。。。鑽石等於4個時候,臥槽,不管咋拿都TM輸,鑽石等於5、6、7時候,臥槽,這回學聰明瞭,我他媽給基友留4個,我不就贏了嗎,5個我就拿1個,6個我就拿2個,7個我就拿3個,臥槽,我聰明。。。那8個怎麼辦呢,手指頭掰一掰,他奶奶的,不管我拿幾個,基友肯定給我剩4個,例如我拿一個,還剩7個,基友肯定拿3個,那TM又給我留4個,我就輸了,我拿2個,基友就拿2個,又給我剩4個,我拿3個,基友拿1個,又給我剩4個。。。怎麼算都輸。。。好吧,栗子舉到這,也差不多明白道理了。。。有4的倍數個鑽石,我怎麼拿都是輸,不是4個倍數個鑽石,我TM的採取正確策略就能贏。。。

演算法實現:

菜鳥我的實現:

public class Solution {
    public boolean canWinNim(int n) {
        if(n%4 == 0){
            return false;
        }else{
            return true;
        }
    }
}
有經驗的人的實現:
public class Solution {
    public boolean canWinNim(int n) {
       return n%4 != 0;
    }
}
高手&專家的實現:
public boolean canWinNim(int n) {
  return (n & 0b11) != 0;
}

public boolean canWinNim(int n) {
    return n>>2<<2!=n;
}

本題在https://leetcode.com/ 中的難易度排的為easy,主要是要分析過程,而亮點就在專家的實現方法了,高階的位運算。

本題摘自:https://leetcode.com/ ,一個不錯的線上演算法學習網站。