Tony's Log

Algorithms, Distributed System, Machine Learning

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

A natural recursion thought.. Please note we can cache intermediate results.

复制代码
class Solution {
    unordered_map<string, bool> hs;
public:
    bool canWin(string s) 
    {
        if(hs.count(s))
        {
          return hs[s];
        }
        
        size_t n = s.length();
        if (n < 2) return false;
        
        bool ret = false;
        int i = 0;
        while(i < n - 1)
        {
          if(s[i] == s[i + 1] && s[i] == '+')      
          {
              string ns = s;
              ns[i] = ns[i + 1] = '-';
              if(!canWin(ns))
              {
                  ret = true;
                  break;
              }
          } 
          i ++;
        }
        
        hs[s] = ret;
        return ret;
    }
};
复制代码

And here is a profound article with deep Game Theory, in case you are interested: 
https://leetcode.com/discuss/64344/theory-matters-from-backtracking-128ms-to-dp-0ms

posted on   Tonix  阅读(145)  评论(0编辑  收藏  举报
努力加载评论中...
点击右上角即可分享
微信分享提示