[leetcode] 22. Generate Parentheses
阿新 • • 發佈:2019-02-01
Givenn pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
For example, givenn = 3, a solution set is:
"((()))", "(()())", "(())()", "()(())", "()()()"
這道題是生成匹配的括號對,題目難度為Medium。
比較直觀的想法是在2*n個位置上逐個放置‘(’或‘)’,通過深度優先的方式生成最終的括號對。這裡需要注意的是隻有在左括號個數小於n時才可以放置‘(’,左括號個數大於右括號個數時才可以放置‘)’,因此需要分別記下左右括號出現的次數,下面程式碼中用lCnt和rCnt表示左右括號的個數。這樣遞迴直到長度達到2*n即找到了一個結果。具體程式碼:
class Solution { void genParenthesis(vector<string>& rst, string curRst, int lCnt, int rCnt, int n) { if(curRst.size() == n*2) { rst.push_back(curRst); return; } else { if(lCnt < n) genParenthesis(rst, curRst+"(", lCnt+1, rCnt, n); if(lCnt > rCnt) genParenthesis(rst, curRst+")", lCnt, rCnt+1, n); } } public: vector<string> generateParenthesis(int n) { vector<string> rst; genParenthesis(rst, "", 0, 0, n); return rst; } };