Generate Parentheses

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:

[
  "((()))",
  "(()())",
  "(())()",
  "()(())",
  "()()()"
]
class Solution {
    func generateParenthesis(_ n: Int) -> [String] {
        var result: [String] = []
        
        helper(&result, "", n, n)
        
        return result
    }
    
    func helper(_ result: inout [String], _ s: String, _ open: Int, _ close: Int) {
        if open == 0 && close == 0 {
            result.append(s)
            return
        }
        
        if open > 0 {
            helper(&result, s + "(", open - 1, close)
        }
        if open < close {
            helper(&result, s + ")", open, close - 1)
        }
    }
}
public class Solution {
    public List<String> generateParenthesis(int n) {
        List<String> result = new ArrayList<>();
        if (n <= 0) {
            return result;
        }
        
        dfs(result, "", n, n);
        return result;
    }
    
    void dfs(List<String> result, String s, int left, int right) {
        if (left == 0 && right == 0) {
            result.add(s);
            return;
        }
        
        if (left > 0) {
            dfs(result, s + "(", left - 1, right);
        }
        
        if (left < right) {
            dfs(result, s + ")", left, right - 1);
        }
    }
}

Hope this helps,
Michael

DigitalOcean Referral Badge