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;
    }
};

 

 posted on 2018-08-05 20:02  平和之心  阅读(118)  评论(0编辑  收藏  举报