码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode "Remove Invalid Parentheses"

时间:2015-11-05 07:37:51      阅读:263      评论:0      收藏:0      [点我收藏+]

标签:

DFS with pruning. The thought flow: for each char, we have 2 choices: pick or not - then DFS.

class Solution {
  int len;
  unordered_set<string> rec;  
  vector<string> ret;
  void go(const string &s, int i, string picked, int cl, int cr)
  {
    // prune
    if(cl < cr) return;
    if((cl - cr) > s.length()) return;
    if((picked.length() + s.length() - i) < len) return;
      
    if(i == s.length())
    {
      if(cl == cr)
      {
        auto clen = picked.length();
        if(clen >= len)
        {
          if(clen > len)
          {
            len = clen;
            rec.clear();
            ret.clear();
          }
          
          if(!rec.count(picked))
          {
            rec.insert(picked);
            ret.push_back(picked);
          }      
        }
      }
      return;
    }
        
    go(s, i + 1, picked, cl, cr); // drop
    
    char c = s[i];
    int ncl = cl, ncr = cr;
    if(c == ()        ncl ++;
    else if (c == ))  ncr ++;
    go(s, i + 1, picked + c, ncl, ncr); // pick
  }
public:
    vector<string> removeInvalidParentheses(string s) {
        len = 0;
    go(s, 0, "", 0, 0);
        return ret;
    }
};

LeetCode "Remove Invalid Parentheses"

标签:

原文地址:http://www.cnblogs.com/tonix/p/4938097.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!