[LeetCode] 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:

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

Analyse:

Solution:

class Solution {
    func generateParenthesis(_ n: Int) -> [String] {
        var output: [String] = [];
        
        self.helper(open:n, close:0, output: &output, text:"")
        
        return output;
    }
    
    func helper(open: Int, close:Int, output: inout [String], text: String) {
        if (open > 0) {
            self.helper(open: open - 1, close: close + 1, output: &output, text:text+"(")
        }
        
        if (close > 0) {
            self.helper(open: open, close: close - 1, output: &output, text:text+")")
        }
        
        if(open == 0 && close == 0) {
            output.append(text);
        }
    }
}

Solution 2:

class Solution {
    func generateParenthesis(_ n: Int) -> [String] {
        var output: [String] = []
        
        handler(output: &output, left: 0, right: 0, text: "", n: n) 
        
        return output
    }
    
    func handler(output: inout [String], left: Int, right: Int, text: String, n: Int) {
        if(left == n && right == n) {
            output.append(text)
            return
        }
        
        if(left < n) {
            handler(output: &output, left: left + 1, right: right, text: text + "(", n: n) 
        }
        
        if(left > right) {
            handler(output: &output, left: left, right: right + 1, text: text + ")", n: n) 
        }
    }
}

Last updated