LeetCode22. Generate Parentheses


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:

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


class Solution {
public:
	vector<string> generateParenthesis(int n) {
		genParenthesis(n, n, "");
		return vs;
	}
private:

	void genParenthesis(int lc, int rc, string s) {
		if (lc == 0 && rc == 0) {
			vs.push_back(s);
			return;
		}
		if (lc > 0) {
			genParenthesis(lc - 1, rc, s + "(");
		} 
		if (rc > lc) {
			genParenthesis(lc, rc - 1, s + ")");
		}
	}
	vector<string> vs;
};


你可能感兴趣的:(LeetCode,回溯法)