22. Generate Parentheses (recursion algorithm)

Claire_ljy發表於2020-04-04

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:

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

AC code:

class Solution {
public:
    vector<string> generateParenthesis(int n) {
        vector<string> v;
        string str = "";
        helper(v, str, 0, 0, n);
        return v;
    }
    void helper(vector<string>& v, string str, int left, int right, int n) {
        if (right == n) {
            v.push_back(str);
            return;
        }
        if (left < n) {
            helper(v, str+'(', left+1, right, n);
        }
        if (right < left) {
            helper(v, str+')', left, right+1, n);
        }
    }
};

Runtime: 0 ms, faster than 100.00% of C++ online submissions for Generate Parentheses.

 

轉載於:https://www.cnblogs.com/ruruozhenhao/p/9741742.html

相關文章