301. 删除无效的括号/C++

在这里插入图片描述

class Solution {
public:
	unordered_set<string> valid;
	void recurse(string s, int index, int leftCount, int rightCount, int leftRem,int rightRem, string str) {
		if (index == s.size()) {
			if (leftRem == 0 && rightRem == 0) 
				valid.insert(str);
		}
		else {
			char c = s[index];
			
			//先不要当前字符
			if (c == '(' && leftRem > 0)
				recurse(s, index + 1, leftCount, rightCount, leftRem - 1, rightRem, str);
			else if (c == ')' && rightRem > 0)
				recurse(s, index + 1, leftCount, rightCount, leftRem, rightRem - 1, str);
			
			//加上当前字符
			str += c;
			if (c != '(' && c != ')') //如果不是括号,则直接加
				recurse(s, index + 1, leftCount, rightCount, leftRem, rightRem, str);
			else if (c == '(')//加左括号
				recurse(s, index + 1, leftCount + 1, rightCount, leftRem, rightRem, str);
			else if (rightCount < leftCount)//只在右括号比zuo括号少时,才加右括号
				recurse(s, index + 1, leftCount, rightCount + 1, leftRem, rightRem, str);
			str.pop_back();//删掉当前字符,回溯
		}
	}
	vector<string> removeInvalidParentheses(string s) {
		//计算出冗余的左括号和右括号数量
		int left = 0, right = 0;
		for (int i = 0; i < s.size(); ++i) {
			if (s[i] == '(')
				++left;
			else if (s[i] == ')') {
				if (left == 0)
					++right;
				else
					--left;
			}
		}
		recurse(s, 0, 0, 0, left, right, "");
		return vector<string>(valid.begin(), valid.end());
	}
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值