【LeetCode】Generate Parentheses

本文介绍了一种生成合法括号组合的算法,通过递归插入方式实现,并探讨了使用卡特兰数解决该问题的可能性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目描述:

Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

For example, given n = 3, a solution set is:

"((()))", "(()())", "(())()", "()(())", "()()()"

要生成括号数为n的所有组合,可以对n-1的每个字符串从最低位到最高位插入"()",用set去重,不过这样重复很多。

class Solution {
public:
	unordered_set<string> dup;
	vector<string> generateParenthesis(int n) {
		if (n == 1)
			return vector<string>(1,"()");
		vector<string> res;
		vector<string> s = generateParenthesis(n - 1);
		for (int i = 0; i < s.size(); i++){
			for (int j = 0; j <= s[i].length(); j++){
				string temp = s[i];
				temp = temp.insert(j, "()");
				if (dup.count(temp))
					continue;
				res.push_back(temp);
				dup.insert(temp);
			}
		}
		return res;
	}
};
还有关于卡特兰数的方法 看这里,学习中……

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值