码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] 22. Generate Parentheses

时间:2016-10-02 00:41:14      阅读:129      评论:0      收藏:0      [点我收藏+]

标签:

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:

[
  "((()))",
  "(()())",
  "(())()",
  "()(())",
  "()()()"
]

解法: backtracking + 递归, 直接套用backtracking的模板解法.
 1 class Solution {
 2 public:
 3     vector<string> generateParenthesis(int n) {
 4         vector<string> allsol;
 5         string sol;
 6         
 7         gp(n, 0, 0, sol, allsol);
 8         return allsol;
 9     }
10     
11     void gp(int n, int nleft, int nright, string& sol, vector<string>& allsol) {
12        if (nleft == n && nright == n){
13            allsol.push_back(sol);
14            return;
15        }
16        
17        if (nleft < n){
18            sol.push_back(();
19            gp(n, nleft+1, nright,sol, allsol);
20            sol.pop_back();
21        }
22        
23        if (nleft > nright){
24            sol.push_back());
25            gp(n, nleft, nright+1, sol,allsol);
26            sol.pop_back();
27        }
28        
29        return;
30     }
31 };

 

[LeetCode] 22. Generate Parentheses

标签:

原文地址:http://www.cnblogs.com/amadis/p/5926547.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!