题目描述
数字
n
代表生成括号的对数,请你设计一个函数,用于能够生成所有可能的并且 有效的 括号组合。示例 1:
输入:n = 3
输出:["((()))","(()())","(())()","()(())","()()()"]
示例 2:输入:n = 1
输出:["()"]
题目解析
本题可以使用回溯法。
首先设置一个全局变量保存结果,再设置一个全局变量暂存字符串
string temp; vector<string> res;
回溯函数为 void getParenthesis(int l,int r,int max),其中l为当前字符串左括号 '(' 的个数,r为右括号 ')' 的个数,max为最大括号对数。
根据回溯法一般套路。
(1)返回边界:temp.length() == 2*max(字符串长度为最大括号对数的两倍),此时将字符串temp加入结果res中。
(2)选择路径:本题每个结点最多只有两个路径,一是当左括号小于max时,可继续增添左括号;二是当右括号小于左括号时,可添加右括号。
(3)路径撤销,让字符串将加入的元素弹出即可。具体代码如下
代码
class Solution {
public:
string temp;
vector<string> res;
void getParenthesis(int l,int r,int max){
if(temp.length() == 2*max){
res.push_back(temp);
}
if(l < max){
temp += '(';
getParenthesis(l+1,r,max);
temp.pop_back();
}if(r < l){
temp += ')';
getParenthesis(l,r+1,max);
temp.pop_back();
}
}
vector<string> generateParenthesis(int n) {
getParenthesis(0,0,n);
return res;
}
};