刷题-括号生成

前方友情提示:这篇博客更多是学习笔记的性质,很多描述可能不清楚、逻辑混乱、语句不顺,甚至说的是错的,所以请酌情阅读,如有错误,欢迎私信我或者在评论区提出,感谢各位!

题目:数据 代表生成括号的对数,请你设计一个函数,用于能够生成所有可能的并且 有效的 括号组合。

示例1:

输入:n=3

输出:["((()))","(()())","(())()","()(())","()()()"]

示例2:

输入:n=1

输出:["()"]

(其中:1<=n<=8)

方法 - 排列组合+回溯
我们用数组res来储存所求的有效括号组合。
        首先,对于有n对括号的有效的括号组合的第一个括号一定是 '(' 最后一个括号一定是 ‘)' 。这样,我们只需判断中间的n-1对括号的组合,选取其中的有效括号组合。

’(‘

’)‘

就是说,我们现在只需考虑将剩下的3个’(‘和3个’)‘放进中间的6个格子,为了得到所有组合的可能,我们用递归来将3个’(‘放进中间6个格子中的任意3个。(这里是关键)

’(‘’(‘’(‘’(‘’)‘

当放满3个’(‘后,我们再把剩下的3个’)‘放进去。

’(‘’)‘’(‘’)‘’(‘’(‘’)‘’)‘

然后用isValid(string)函数来判断是否有效括号组合(这个函数当然是自己定义的啦)。

判断是否有效括号组合的isValid()函数

bool isValid(string s) {
	int n = s.size();
	if (n % 2 == 1) {
		return false;
	}

	unordered_map<char, char> pairs = {
		{')', '('},
		{']', '['},
		{'}', '{'}
	};
	stack<char> stk;
	for (char ch : s) {
		if (pairs.count(ch)) {
			if (stk.empty() || stk.top() != pairs[ch]) {
				return false;
			}
			stk.pop();
		}
		else {
			stk.push(ch);
		}
	}
	return stk.empty();
}

关键的递归(用递归来获得所有的’(‘在中间位置的组合)

void dfs(vector<char>&temp, int pos, int depth, vector<string>&res) {
	temp[pos] = '(';
	if (depth == temp.size() / 2-1)
	{
		string s;
		for (int i = 1; i < temp.size() - 1; i++)
			if (temp[i] == '0')
				temp[i] = ')';
		for (int i = 0; i < temp.size(); i++)
			s += temp[i];
		if (isValid(s))
			res.push_back(s);
		for (int i = 1; i < temp.size() - 1; i++)
		{
			if (temp[i] == ')')
				temp[i] = '0';
		}
		temp[pos] = '0';
		return;
	}
	else
	{

		for (int i = pos + 1; i < temp.size() - 1; i++)
		{
			dfs(temp, i, depth + 1, res);
		}

	}
	temp[pos] = '0';
	return;
}

通过这两个函数的调用,我们就可以获得我们所需的答案。

完整源码:

class Solution {
private:
bool isValid(string s) {
	int n = s.size();
	if (n % 2 == 1) {
		return false;
	}

	unordered_map<char, char> pairs = {
		{')', '('},
		{']', '['},
		{'}', '{'}
	};
	stack<char> stk;
	for (char ch : s) {
		if (pairs.count(ch)) {
			if (stk.empty() || stk.top() != pairs[ch]) {
				return false;
			}
			stk.pop();
		}
		else {
			stk.push(ch);
		}
	}
	return stk.empty();
}
void dfs(vector<char>&temp, int pos, int depth, vector<string>&res) {
	temp[pos] = '(';
	if (depth == temp.size() / 2-1)
	{
		string s;
		for (int i = 1; i < temp.size() - 1; i++)
			if (temp[i] == '0')
				temp[i] = ')';
		for (int i = 0; i < temp.size(); i++)
			s += temp[i];
		if (isValid(s))
			res.push_back(s);
		for (int i = 1; i < temp.size() - 1; i++)
		{
			if (temp[i] == ')')
				temp[i] = '0';
		}
		temp[pos] = '0';
		return;
	}
	else
	{

		for (int i = pos + 1; i < temp.size() - 1; i++)
		{
			dfs(temp, i, depth + 1, res);
		}

	}
	temp[pos] = '0';
	return;
}

public:
vector<string> generateParenthesis(int n) {
	vector<string> res;
	vector<char> temp(2 * n, '0');
	temp[0] = '('; temp[2 * n - 1] = ')';

	if (n == 1)
	{
		string s;
		for (auto a : temp)
			s += a;
		res.push_back(s);
		return res;
	}

	for (int i = 1; i < 2 * n - 1; i++)
		dfs(temp, i, 1,res);

	return res;
}
};

共勉!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值