leetcode 301 : Remove Invalid Parentheses
2015-11-06 21:14
295 查看
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、解题如下:
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); } } } };
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- 关于指针的一些事情
- c++ primer 第五版 笔记前言
- share_ptr的几个注意点
- 只有程序员看的懂的面试圣经|如何拿下编程面试
- 下一次技术面试时要问的 3 个重要问题
- Lua中调用C++函数示例
- Lua教程(一):在C++中嵌入Lua脚本
- Lua教程(二):C++和Lua相互传递数据示例
- PHP程序员面试 切忌急功近利(更需要注重以后的发展)
- C++联合体转换成C#结构的实现方法
- C++编写简单的打靶游戏
- C++ 自定义控件的移植问题
- C++变位词问题分析
- C/C++数据对齐详细解析
- C++基于栈实现铁轨问题
- C++中引用的使用总结
- 使用Lua来扩展C++程序的方法
- C++中调用Lua函数实例
- Lua和C++的通信流程代码实例