zoukankan      html  css  js  c++  java
  • LeetCode "Remove Invalid Parentheses"

    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;
        }
    };
  • 相关阅读:
    Redis 连接命令
    Redis 脚本
    Redis 事务
    Redis 发布订阅
    Redis HyperLogLog
    Redis 有序集合(sorted set)
    Redis 集合(Set)
    Redis 列表(List)
    Redis 哈希(Hash)
    特定消费者的限制流量
  • 原文地址:https://www.cnblogs.com/tonix/p/4938097.html
Copyright © 2011-2022 走看看