Generate Parentheses 括号生成

给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合。

例如,给出 = 3,生成结果为:

[
  "((()))",
  "(()())",
  "(())()",
  "()(())",
  "()()()"
]

思路:采用回溯的方法,每次把当前已经加入左括号的个数left和右括号的个数right计入函数参数中,如果left等于n并且right等于n,就把当前的字符串curStr加入结果res中。否则如果当前左括号的个数left小于n,就递归调用自身,并传入当前字符串curStr+'(',如果当前右括号数right小于左括号数left,就递归调用自身,传入当前字符串为curStr+')'

参考代码:

class Solution {
public:
void generateParenthesisCore(int left, int right, vector<string> &res, string &curStr,int length) {
	if (left == length && right == length) {
		res.push_back(curStr);
		return;
	}
	if (left < length) {
		curStr.push_back('(');
		generateParenthesisCore(left + 1, right, res, curStr, length);
		curStr.pop_back();
	}
	if (right < left) {
		curStr.push_back(')');
		generateParenthesisCore(left, right+1, res, curStr, length);
		curStr.pop_back();
	}
}
vector<string> generateParenthesis(int n) {
	vector<string> res;
	string curStr = "";
	generateParenthesisCore(0, 0, res, curStr,n);
	return res;
}
};

猜你喜欢

转载自blog.csdn.net/qq_26410101/article/details/81451969