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

22. Generate Parentheses

时间:2018-08-05 21:35:26      阅读:168      评论:0      收藏:0      [点我收藏+]

标签:span   UNC   string   (())   push   str   div   nbsp   form   

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:

[
  "((()))",
  "(()())",
  "(())()",
  "()(())",
  "()()()"
]
// size表示栈的size
class Solution {
    void dfs(int n, int size, string path, vector<string> &ans) {
        if(path.size() == 2*n) {
            if(size == 0)
                ans.push_back(path);
            return ;
        }
        // try to add ‘(‘
        path.push_back(();
        dfs(n, size+1, path, ans);
        path.pop_back();
        // ‘)‘
        if(size > 0) {
            path.push_back());
            dfs(n, size-1, path, ans);
            path.pop_back();
        }
    }
public:
    vector<string> generateParenthesis(int n) {
        vector<string> ans;
        dfs(n, 0, "", ans);
        return ans;
    }
};

 

22. Generate Parentheses

标签:span   UNC   string   (())   push   str   div   nbsp   form   

原文地址:https://www.cnblogs.com/vegg117/p/9426941.html

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