九章算法 - 四、博弈型動態規劃 394.

394. Coins in a Line

提示: 可以證明, 當硬幣數目是3的倍數的時候, 先手玩家必敗, 否則他必勝.

            當硬幣數目是3的倍數時, 每一輪先手者拿a個, 後手者拿3-a個即可, 後手必勝.

             若不是3的倍數, 先手者可以拿1或2個, 此時剩餘硬幣個數就變成了3的倍數.

             如果用動態規劃的方法,在當下局面走出一步可以讓對方必敗,而不必去在意具體應該怎麼取。注意,如果不設置f的初               始 大小67%的數據會超時。

答案:

class Solution {
public:
    /**
     * @param n: An integer
     * @return: A boolean which equals to true if the first player will win
     */
    bool firstWillWin(int n) {
        return n % 3;
    }
};
class Solution {
public:
    /**
     * @param n: An integer
     * @return: A boolean which equals to true if the first player will win
     */
    bool firstWillWin(int n) {
        // write your code here
        if(n == 0) return false;
        if(n <= 2 ) return true;
        
        vector<bool> f(n + 1);
        f[0] = false;
        f[1] = true;
        f[2] = true;
        
        for(int i = 3; i <= n; i++){
            f[i] = (f[i - 1] == false || f[i - 2] == false);
        }
        return f[n];
    }
};

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章