Wednesday, June 15, 2016

Generate Parenthesis -- LeetCode

[Question]
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
Example:
Given n = 3, a solution set is:
"((()))", "(()())", "(())()", "()(())", "()()()"
 
[Analysis]
Generate all combination using recursion. Simply insert "(" as many as possible first, then try to insert ")" as alternative path. When n = 3, the recursion will look like:
  ((()))
  (()())
  (())()
  ()(())
  ()()()
--> recursion depth -->

[Solution]
class Solution {
public:
    /**
     * @param n n pairs
     * @return All combinations of well-formed parentheses
     */
    vector<string> generateParenthesis(int n) {
        // Write your code here
        vector<string> res;
        string s;
        helper(s, res, 0, 0, n);
        return res;
    }
    void helper(string s, vector<string> &res, int l, int r,int n){
        if(r==n){
            res.push_back(s);
        }
        else if(l==n){
            helper(s+')', res, l, r+1,n);
        }
        else{
            helper(s+'(', res, l+1, r, n);
            if(l>r)
                helper(s+')',res, l, r+1, n);

        }
    }
};

No comments:

Post a Comment