Created
January 12, 2020 20:26
-
-
Save alexpersian/f9a851aa9210398b8c4c216d01ea66d4 to your computer and use it in GitHub Desktop.
Much simpler solution for generating a string of balanced parentheses of length (n * 2).
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
final class Generator { | |
private var store = [[""]] | |
func genBalanced(_ n: Int) -> [String] { | |
if n < store.count { | |
return store[n] | |
} | |
var result: [String] = [] | |
for i in 0..<n { | |
for x in genBalanced(i) { | |
for y in genBalanced(n - i - 1) { | |
result.append("(" + x + ")" + y) | |
} | |
} | |
} | |
store.append(result) | |
return store[n] | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment