LeetCode301. 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: [""]

这道题参考了LeetCode上的解答:here。为了是我们的程序能够在规定的时间完成,我们右增加了剪枝操作,然后为了能够尽可能减少内存使用,我们使用了类成员变量以较少递归参数。

class Solution {
public:
	vector<string> removeInvalidParentheses(string s) {
		remain = 0;
        our = s;
		helper(0, 0, "", 0);
		vector<string> vRes(res.begin(), res.end());
		return vRes;
	}
private:
	int remain;
    set<string> res;
    string our;
	void helper(int left, int right, string candidate, int index) {
		if (index == our.size()) {
			if (left == right) {
				if (candidate.size() >= remain) {
					remain = candidate.size();

					if (candidate.size() > remain)
						res = set<string>();
					res.insert(candidate);
				}
			}
			return;
		}

		if (left < right) return;
        if (left-right > our.size() - index) return;
        
		string newCan = candidate + our[index];
		int newIndex = index + 1;
		if (our[index] != '(' && our[index] != ')') {
			helper(left, right, newCan, newIndex);
		}
		else {
			if (our[index] == '(') {
				helper(left + 1, right, newCan, newIndex);
				helper(left, right, candidate, newIndex);
			}
			else {
				helper(left, right + 1, newCan, newIndex);
				helper(left, right, candidate, newIndex);
			}
		}
		return;
	}
};

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值