zoukankan      html  css  js  c++  java
  • 301. Remove Invalid Parentheses

    Remove the minimum number of invalid parentheses in order to make the input string valid. Return all possible results.

    Note: The input string may contain letters other than the parentheses ( and ).

    Example 1:

    Input: "()())()"
    Output: ["()()()", "(())()"]
    

    Example 2:

    Input: "(a)())()"
    Output: ["(a)()()", "(a())()"]
    

    Example 3:

    Input: ")("
    Output: [""]

    Approach #1: C++.

    class Solution {
    public:
        vector<string> removeInvalidParentheses(string s) {
            int l = 0;
            int r = 0;
         // calculate the mismatch parentheses. for (char c : s) { l += (c == '('); if (l == 0) { r += (c == ')'); } else { l -= (c == ')'); } } vector<string> ans; dfs(s, 0, l, r, ans); return ans; } private: bool isValid(string& s) { int count = 0; for (char c : s) { if (c == '(') count++; if (c == ')') count--; if (count < 0) return false; } return count == 0; } void dfs(string s, int start, int l, int r, vector<string>& ans) { if (l == 0 && r == 0) { if (isValid(s))  // judge the string is valid. ans.push_back(s); return; } for (int i = start; i < s.length(); ++i) { if (i != start && s[i] == s[i-1]) continue;
            // s[i] is '(' or ')' if (s[i] == '(' || s[i] == ')') { string curr = s; curr.erase(i, 1); if (r > 0) dfs(curr, i, l, r-1, ans); else if (l > 0) dfs(curr, i, l-1, r, ans); } } } };

      

    Analysis:

    step1: compute min number of '(' and ')' to remove, unbalanced ')' + unblanced '('

    step2: try all possible ways to remove r '(' and l ')'. Remove '(' first to make prefix valid.

    step3: when r == 0 and l == 0, judging the string is or not fulfiled conditions.

    永远渴望,大智若愚(stay hungry, stay foolish)
  • 相关阅读:
    pyqt动画的使用
    pyqt 自定义信号
    设计工具- QtDesigner
    样式控制-QSS 样式表
    布局管理之 QStackedLayout (堆 布局)
    布局管理之 QGridLayout (网格布局)
    布局管理之 QFormLayout (表单布局)
    看代码中
    公司同事好坑
    我要多开梦幻手游PC端(梦幻手游PC端多开的简单分析及实现办法)
  • 原文地址:https://www.cnblogs.com/h-hkai/p/10099455.html
Copyright © 2011-2022 走看看