From 7fc48ff5bbddf394b4751551cfc5a8f3a371908c Mon Sep 17 00:00:00 2001 From: Soap Date: Sun, 18 Aug 2019 14:43:20 -0700 Subject: [PATCH] Refactor Solution to GenerateParentheses --- DP/GenerateParentheses.swift | 30 ++++++++++++++---------------- 1 file changed, 14 insertions(+), 16 deletions(-) diff --git a/DP/GenerateParentheses.swift b/DP/GenerateParentheses.swift index 90b3ae8c..8e0b65c8 100644 --- a/DP/GenerateParentheses.swift +++ b/DP/GenerateParentheses.swift @@ -7,30 +7,28 @@ class GenerateParentheses { func generateParenthesis(_ n: Int) -> [String] { - var paths = [String](), path = [Character](repeating: " ", count: 2 * n) + guard n > 0 else { + return [String]() + } + + var paths = [String](), path = "" - helper(&paths, &path, n, n, 0) + dfs(&paths, path, n, n) return paths } - func helper(_ paths: inout [String], _ path: inout [Character], _ leftCount: Int, _ rightCount: Int, _ index: Int) { - if leftCount < 0 || leftCount > rightCount { - return - } - - if leftCount == 0 && rightCount == 0 { - paths.append(String(path)) + private func dfs(_ paths: inout [String], _ path: String, _ leftRemaining: Int, _ rightRemaining: Int) { + if rightRemaining == 0 { + paths.append(path) return } - if leftCount > 0 { - path[index] = "(" - helper(&paths, &path, leftCount - 1, rightCount, index + 1) + if leftRemaining > 0 { + dfs(&paths, path + "(", leftRemaining - 1, rightRemaining) } - if rightCount > leftCount { - path[index] = ")" - helper(&paths, &path, leftCount, rightCount - 1, index + 1) + if rightRemaining > leftRemaining { + dfs(&paths, path + ")", leftRemaining, rightRemaining - 1) } } -} \ No newline at end of file +}