22、括号生成

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

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

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

方法一:动态规划

思路:

【1】对于已有字符串str添加'('还是‘)’

【2】若左括号数小于n可以添加左括号'('

【3】若左括号数大于右括号数添加右括号')'

【4】递归结束条件是字符串长度等于2*n

vector<string> vecStr;
void dpStr(int count1, int count2, int times, string str) {		//'('数量,')'数量
	if (str.length() == 2 * times) {
		vecStr.push_back(str);
	}
	else {
		if (count1 < times) {	//'('数量未满,可以填充
			dpStr(count1 + 1, count2, times, str + '(');
		}
		if (count1 > count2) {	//'('数量大于')',可以添加')'
			dpStr(count1, count2 + 1, times, str + ')');
		}
	}
}
vector<string> generateParenthesis(int n) {
	dpStr(0, 0, n, "");
	return vecStr;
}

猜你喜欢

转载自blog.csdn.net/hello_noob/article/details/89811428