Skip to content

Commit

Permalink
Refactor Solution to GenerateParentheses
Browse files Browse the repository at this point in the history
  • Loading branch information
soapyigu authored Aug 18, 2019
1 parent 5c9b21b commit 7fc48ff
Showing 1 changed file with 14 additions and 16 deletions.
30 changes: 14 additions & 16 deletions DP/GenerateParentheses.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}
}
}

0 comments on commit 7fc48ff

Please sign in to comment.