LeetCode 22. Generate Parentheses

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:

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

简单搜索,用dfs列出所有情况就行了

class Solution {
    
    void dfs(vector<string> &vec, string str, int x, int y)
    {
        if(x == 0 && y == 0)
        {
            vec.push_back(str);
            return ;
        }
        
        if(x == y)
            dfs(vec, str+'(', x-1, y);
        else
        {
            if(x > 0)
                dfs(vec, str+'(', x-1, y);
            dfs(vec, str+')', x, y-1);
        }
    }
    
public:
    vector<string> generateParenthesis(int n) {
        string str;
        vector<string>vec;
        int x = n, y = n;
        dfs(vec, str, x,  y);
        return vec;
    }
};
原文地址:https://www.cnblogs.com/aiterator/p/6592081.html