Description
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
Example
For example, given n = 3, a solution set is:
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]
Solution 1(C++)
class Solution{
public:
vector<string> generateParenthesis(int n) {
vector<string> res;
helper(res, "", n, 0);
return res;
}
private:
void helper(vector<string>& res, string s, int n, int m){
if(n==0 && m==0) { res.push_back(s); return; }
if(n>0) helper(res, s+'(', n-1, m+1);
if(m>0) helper(res, s+')', n, m-1);
}
};
算法分析
解法一:
解法一其實是利用回溯遞歸來解決問題的。一看就都懂,但是就是不太好想。利用了n與m來記錄正括號與反括號的數量。n > 0時,當添加了一個正括號,n就減少,但是相應的m加一;m>0,可以添加一個反括號,m減少,但是n不變。當n與m都爲0的時候,說明正括號與反括號都添加完畢。
程序分析
略。