Remove Invalid Parentheses
2016-03-11 01:34
344 查看
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
Examples:
[/code]
Note: The input string may contain letters other than the parentheses
(and
).
Examples:
"()())()" -> ["()()()", "(())()"] "(a)())()" -> ["(a)()()", "(a())()"] ")(" -> [""] [code]class Solution { public: vector<string> removeInvalidParentheses(string s) { set<string> temp; int n = s.length(); int left_remove = 0; int right_remove = 0; for (int i = 0; i < n; i++) { if (s[i] == '(') { left_remove++; } else if (s[i] == ')') { if (left_remove > 0) { left_remove--; } else { right_remove++; } } } visit(s, n, 0, left_remove, right_remove, 0, 0, "", temp); vector<string> result(temp.begin(), temp.end()); return result; } private: void visit(string &s, int n, int pos, int left_remove, int right_remove, int left_count, int right_count, string buf, set<string> &temp) { if (n == pos) { if (left_remove == 0 && right_remove == 0) { temp.insert(buf); } return; } if (s[pos] == '(') { if (left_remove > 0) { visit(s, n, pos+1, left_remove-1, right_remove, left_count, right_count, buf, temp); } visit(s, n, pos+1, left_remove, right_remove, left_count+1, right_count, buf+s[pos], temp); } else if (s[pos] == ')') { if (right_remove > 0) { visit(s, n, pos+1, left_remove, right_remove-1, left_count, right_count, buf, temp); } if (left_count <= right_count) { return; } visit(s, n, pos+1, left_remove, right_remove, left_count, right_count+1, buf+s[pos], temp); } else { visit(s, n, pos+1, left_remove, right_remove, left_count, right_count, buf+s[pos], temp); } } };
[/code]
相关文章推荐
- 多线程实现三种方法
- 组合模式
- 归并排序--Java实现
- 接口的使用
- 通过寄生组合式继承创建js的异常类
- ZOJ 1094 Matrix Chain Multiplication
- 稀疏矩阵的转置和快速转置
- set map list vector
- CC2541 Large OAD 空中升级方式
- Android中的“Application”,“Task”,“Activities”的关系
- 【博客分享】优秀的有趣的博客
- hibernate的批量更新、批量删除
- spring的RestTemplate的配置及使用
- LESS
- EtherCAT介绍
- POJ-2771-Guardian of Decency-求二分图最大独立集(匈牙利算法)
- POJ 1988 Cube Stacking并查集
- API幂等性设计
- WCF传输大数据问题讨论
- java将字符串进行反转单词需正确拼写