Alice and Bob continue their games with stones. There is a row of n stones, and each stone has an associated value. You are given an integer array stones, where stones[i] is the value of the ith stone.
Alice and Bob take turns, with Alice starting first. On each turn, the player may remove any stone from stones. The player who removes a stone loses if the sum of the values of all removed stones is divisible by 3. Bob will win automatically if there are no remaining stones (even if it is Alice's turn).
Assuming both players play optimally, return true if Alice wins and false if Bob wins.
題目表示Alice和Bob(以下簡稱A和B)在玩一個遊戲:
我的解題思路是
0.因為玩家可以隨意選擇石頭,所以遍歷所有可能性會很暴力...要另尋他方!!
class Solution {
public boolean stoneGameIX(int[] stones) {
int c0 = 0, c1 = 0, c2 = 0;
// 計算各個餘數的石頭個數
for (int stone : stones) {
if (stone % 3 == 0) {
c0++;
} else if (stone % 3 == 1) {
c1++;
} else {
c2++;
}
}
// 如果餘數為0的石頭數目為偶數
if (c0 % 2 == 0) {
if (c1 == 0 || c2 == 0) {
return false;
}
return true;
} else {
// 如果餘數為0的石頭數目為奇數
if (Math.abs(c1 - c2) > 2 || Math.abs(c1 - c2)%2 == 0) {
return false;
}
return true;
}
}
}
好累,我覺得好難。
其實我的邏輯錯了好幾次,陸續修正了一個小時才成功。晚安。