Leetcode 22 括号生成
题目描述:
给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合。
例如,给出 n = 3,生成结果为:
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]
思路
暴力枚举轻而易举,但是这样的复杂度是吃不消的,也不是这道题的本意
一个简单的方法就是回溯 也就是DFS那种思想
对于 n 对括号,也就是2n的长度,每一个位置只有两种可能‘(’和 ‘)’
,所以只需要在当前位置判断一下
他是否可以为两者或者两者之一
条件也很容易得出
当左括号个数没有达到n时 ‘(‘ 可取 ,即左括号是没有什么限制的(除了个数)
当存在未匹配左括号时 ‘)‘ 可取,因为每一个左括号都与唯一一个右括号匹配
这里需要对有效括号有个明确概念,有效即每一个(都可以找到一个)即可。
代码
class Solution {
public:
vector<string> generateParenthesis(int n) {
vector<string> res;
string temp = "";
creatBracket(n,0,0,0,temp,res);
return res;
}
// size: n ;
// index : 当前的位置
// numberOfLeft : 已经用的左括号个数
// numberOfMatch : 未匹配好的个数
void creatBracket(int size, int index, int numberOfLeft,int numberOfMatch,string tar, vector<string> &res)
{
if(index == 2*size)
{
res.push_back(tar);
return;
}
if(numberOfMatch > 0)
creatBracket(size,index+1,numberOfLeft,numberOfMatch-1,tar+')',res);
if(numberOfLeft < size)
creatBracket(size,index+1,numberOfLeft+1,numberOfMatch+1,tar+'(',res);
}
};
更多方法
官方题解:https://leetcode-cn.com/articles/generate-parentheses/