leetcode 301 : Remove Invalid Parentheses

来源:互联网 发布:修改oracle默认端口 编辑:程序博客网 时间:2024/05/16 11:12

1、原题如下:
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 ).

Examples:
“()())()” -> [“()()()”, “(())()”]
“(a)())()” -> [“(a)()()”, “(a())()”]
“)(” -> [“”]

2、解题如下:

class Solution {public:    vector<string> removeInvalidParentheses(string s) {        unordered_set<string> result;        int left_erase=0;        int right_erase=0;        for(auto c:s)        {            if(c=='(') {left_erase++;}            if(c==')')             {                if(left_erase!=0)                    left_erase--;                else                    right_erase++;            }        }        traverse(s,0,left_erase,right_erase,0,"",result);        return vector<string> (result.begin(),result.end());    }    void traverse(string s,int count,int left_erase,int right_erase,int pair,string tmp,unordered_set<string>& result)    {        if(count==s.size())        {            if(left_erase==0&&right_erase==0&&pair==0)                result.insert(tmp);            return;        }        if(s[count]!='('&&s[count]!=')')        {            traverse(s,count+1,left_erase,right_erase,pair,tmp+s[count],result);        }        else if(s[count]=='(')        {            if(left_erase>0)            {                traverse(s,count+1,left_erase-1,right_erase,pair,tmp,result);            }            traverse(s,count+1,left_erase,right_erase,pair+1,tmp+s[count],result);        }        else        {            if(right_erase>0)            {                traverse(s,count+1,left_erase,right_erase-1,pair,tmp,result);            }            if(pair>0)            {                traverse(s,count+1,left_erase,right_erase,pair-1,tmp+s[count],result);            }        }    }};
0 0