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: /* * 采用递归,open 代表左括号的个数, close 代表右括号的个数,给定n个左括号,和n个右括号 * 结束条件就是左括号已经全部加入字符串,这时候,将剩下的右括号也加入字符串 * 保证一个字符串中右括号的个数小于左括号的个数,同时左括号先出现 * */ vector<string> generateParenthesis(int n) { vector<string> res; string str = ""; cmn(res, str, n, n); return res; } void cmn (vector<string>& res, string str, int open, int close) { //判断结束条件 if (open == 0) { while (close) { str += ‘)‘; close--; } res.push_back(str); return; } //如果左括号存在,就将左括号加入字符串,这个判断不是必须的,可以去掉 if (open) { cmn(res, str+‘(‘, open-1, close); } //如果剩下的右括号个数大于左括号的个数,就将右括号放入字符串 if (close > open) { cmn(res, str+‘)‘, open, close-1); } } };
原文:http://www.cnblogs.com/SpeakSoftlyLove/p/5119732.html