首页 > 代码库 > 【LeetCode】022. Generate Parentheses

【LeetCode】022. 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:

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

  

题解:

Solution 1 ()

class Solution {
public:
    void dfs(int n, int level, int sum, vector<string>& vs, string& s) {
        if(sum<0) { 
            sum = 0;
            return;
        }
        if(level >= n) {
            if(sum !=0 ) return;
            vs.push_back(s);
            return;
        }
        s.push_back(();
        sum++;
        dfs(n, level+1, sum, vs, s);
        s.pop_back();
        sum--;
        
        s.push_back());
        sum--;
        dfs(n, level+1, sum, vs, s);
        s.pop_back();
        sum++;
    }
    vector<string> generateParenthesis(int n) {
        vector<string> vs;
        string s;
        if(n<=0) return vs;
        dfs(2*n, 0, 0, vs, s);     
        return vs;   
    }
};

 

【LeetCode】022. Generate Parentheses