【題目】
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:
"((()))", "(()())", "(())()", "()(())", "()()()"
【分析】
顯然是個遍歷的過程,但是如何遍歷是個問題。遍歷,我們經常可以使用遞歸的方式解決。遞歸,套路是先寫出跳出條件,然後再寫其他遞歸調用程序部分。這個題目中跳出條件明顯是當左括號(和右括號)都使用完的時候,壓入結果,返回。那麼剩下的部分呢?這個時候就要結合具體問題,具體分析了。括號匹配最核心的是,生成的括號一定要是well-formed。這就需要當前生成的cur字符串中,一定要保證左括號的數量小於右括號數量。所以,如果左括號數量m不等於0,則可以繼續放置,而當左括號數量小於右括號數量,並且右括號數量不等於0的時候,纔可以放置右括號!
【代碼】
運行時間:5ms
class Solution {
public:
vector<string> generateParenthesis(int n) {
vector<string> res;
if(n == 0)
return res;
string cur = "";
fun(res, cur, n, n);
return res;
}
void fun(vector<string>& res, string cur, int m, int n)
{
if(m == 0 && n == 0)
{
res.push_back(cur);
return;
}
if(m != 0)
{
fun(res, cur + '(', m-1, n);
}
if(m < n && n != 0) // "m < n" ensure the generated parantheses are well-formed
{
fun(res, cur + ')', m, n-1);
}
}
};