Remove Invalid Parentheses
来源:互联网 发布:视频软件哪个好 编辑:程序博客网 时间:2024/06/04 19:08
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())()"]")(" -> [""]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); } }};
0 0
- [LeetCode] Remove Invalid Parentheses
- LeetCode -- Remove Invalid Parentheses
- Remove Invalid Parentheses--Nice
- Remove Invalid Parentheses
- leetcode Remove Invalid Parentheses
- Leetcode214: Remove Invalid Parentheses
- LeetCode Remove Invalid Parentheses
- [Leetcode]Remove Invalid Parentheses
- 301. Remove Invalid Parentheses
- leetcode:Remove Invalid Parentheses
- leetcode - Remove Invalid Parentheses
- Remove Invalid Parentheses
- 【Leetcode】Remove Invalid Parentheses
- LeetCode:Remove Invalid Parentheses
- Remove Invalid Parentheses
- Remove Invalid Parentheses
- 301. Remove Invalid Parentheses
- Remove Invalid Parentheses
- ZOJ 1094 Matrix Chain Multiplication
- 组合模式
- 归并排序--Java实现
- 多线程实现三种方法
- Clang 宏定义初探(一)
- Remove Invalid Parentheses
- C++ Exceptional Item 20 Class Mechanics
- Java堆、栈、方法区、常量池
- 判断当前应用程序处于前台还是后台 ANDROID
- [并查集] hdu1272 小希的迷宫
- ELM的算法及伪代码
- 搭建linux服务器之Vim配置
- Clang 宏定义初探(二)
- POJ-1422-Air Raid-求最小路径覆盖(匈牙利算法)