Tony's Log

Algorithms, Distributed System, Machine Learning

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

Recursion + Memorized Search(DP). And apparently, the code below can be iterative with only 3 vars - DP.

class Solution {
    unordered_map<int, bool> cache;
public:
    bool go(int n)
    {
        if (n <=0) return false;
        if (n < 3) return true;

        if(cache.find(n) == cache.end())
        {
            cache[n] = !go(n - 1) || !go(n - 2);
        }
        return cache[n];
    }
    /**
     * @param n: an integer
     * @return: a boolean which equals to true if the first player will win
     */
     bool firstWillWin(int n) {
        return go(n);
    }
};
posted on 2015-10-03 12:34  Tonix  阅读(136)  评论(0编辑  收藏  举报