22. Generate Parentheses (recursion algorithm)

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.

 

posted @ 2018-10-04 10:43  Veritas_des_Liberty  阅读(185)  评论(0编辑  收藏  举报