Generate Parentheses - Swift 10 Lines


  • 0
    M

    The trick is in understanding that all parenthesis must be balanced. The problem can be simplified when it is understood that a string can only add an opening or closing parenthesis. So given that, one must determine which of two are valid to add and recurse on that.

    class Solution {
        func generateParenthesis(_ n: Int) -> [String] {
            return g("(", n - 1, n)
        }
        
        func g(_ str: String, _ o: Int, _ c: Int) -> [String] {
            if o == 0 && c == 0 { return [str] }
            return (o > 0 ? g(str + "(", o - 1, c) : []) + (c > 0 && c > o ? g(str + ")", o, c - 1 )  : [])
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.