Skip to content

Instantly share code, notes, and snippets.

@alexpersian
Created January 12, 2020 20:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexpersian/f9a851aa9210398b8c4c216d01ea66d4 to your computer and use it in GitHub Desktop.
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).
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