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:
"((()))", "(()())", "(())()", "()(())", "()()()"
Cracking the Code Interview里面也有,涉及到DFS的题目一律头疼,咋才能明白些呢?虽然这个做出来了。
class Solution { public: vector<string> generateParenthesis(int n) { vector<string> result; string comb; generateParenthesisUtil(result, comb, n, n); return result; } void generateParenthesisUtil(vector<string> &result, string &comb, int left, int right) { if (left == 0 && right == 0) { result.push_back(comb); } else { if (left > 0) { comb.push_back('('); generateParenthesisUtil(result, comb, left - 1, right); comb.pop_back(); } if (right > left) { comb.push_back(')'); generateParenthesisUtil(result, comb, left, right - 1); comb.pop_back(); } } } };
================第二次================
class Solution { public: vector<string> generateParenthesis(int n) { vector<string> result; string comb; generate(result, comb, n, n); return result; } void generate(vector<string> &result, string &comb, int left, int right) { if (left == 0 && right == 0) { result.push_back(comb); return; } if (left > 0) { comb.push_back('('); generate(result, comb, left - 1, right); comb.pop_back(); } if (right > 0 && left < right) { comb.push_back(')'); generate(result, comb, left, right - 1); comb.pop_back(); } } };
class Solution { public: vector<string> generateParenthesis(int n) { vector<vector<string>> result; result.push_back(vector<string>(1, "")); result.push_back(vector<string>(1, "()")); for (int i = 2; i <= n; ++i) { result.push_back(vector<string>()); for (int j = 0; j < i; ++j) { vector<string>& left = result[j]; vector<string>& right = result[i-j-1]; for (int k = 0; k < left.size(); ++k) { for (int h = 0; h < right.size(); ++h) { result[i].push_back(left[k] + "(" + right[h] + ")"); } } } } return result[n]; } };
class Solution { public: vector<string> generateParenthesis(int n) { vector<string> result; stack<string> validParts; stack<int> usedRight; validParts.push("("); usedRight.push(0); while (!validParts.empty()) { string part = validParts.top(); validParts.pop(); int right = usedRight.top(); usedRight.pop(); if (right == n) { result.push_back(part); } if (part.size() - right < n) { validParts.push(part + "("); usedRight.push(right); } if (right * 2 < part.size()) { validParts.push(part + ")"); usedRight.push(right + 1); } } return result; } };