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:

"((()))", "(()())", "(())()", "()(())", "()()()"

递归生成

判断 l == n 记录结果,当 r < l 时可以增加右括号

class Solution {
private:
    vector<string> result;
public:
    vector<string> generateParenthesis(int n) {
        dfs("", 0, 0, n);
        return result;
    }
    void dfs(string s, int l, int r,int n){
        if(l == n) {
            result.push_back(s.append(n - r,')'));
            return;
        }
        dfs(s+"(", l + 1, r, n);
        if(r < l) dfs(s+")", l, r + 1, n);
    }
};

你可能感兴趣的:(22. Generate Parentheses)