Swift solution, 19ms


  • 0
    S

    Swift implementation of brobins9's Java solution.

    class Solution {
    
        func generateParenthesis(_ n: Int) -> [String] {
            var results = [String]()
            
            generateParenthesis(&results, n, "", 0, 0, 0)
            
            return results
        }
        
        private func generateParenthesis(_ results: inout [String], _ n: Int, _ str: String, _ strLen: Int,  _ open: Int, _ closed: Int) {
            
            if strLen == n * 2 {
                results.append(str)
            } else {
                if open < n {
                    generateParenthesis(&results, n, "\(str)(", strLen + 1, open + 1, closed)
                }
                if closed < open {
                    generateParenthesis(&results, n, "\(str))", strLen + 1, open, closed + 1)
                }
            }
            
        }
        
    }
    

Log in to reply
 

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