Skip to content

Instantly share code, notes, and snippets.

@spurscho
Created January 19, 2020 12:40
Show Gist options
  • Save spurscho/810f0fb7c23dde39584e0c7d5d5899f7 to your computer and use it in GitHub Desktop.
Save spurscho/810f0fb7c23dde39584e0c7d5d5899f7 to your computer and use it in GitHub Desktop.
22. Generate Parentheses
class Solution {
func generateParenthesis(_ n: Int) -> [String] {
var result = [String]()
if(n == 0) {
return result
}
var str = ""
generateParenthesisUtil(&result,str,n,0,0)
return result
}
func generateParenthesisUtil(_ result:inout [String],_ str: String, _ n:Int, _ left:Int, _ right:Int) {
if right == n {
result.append(str)
return
}
if (left < n) {
let s = str + "("
generateParenthesisUtil(&result,s, n, left + 1, right)
}
if(left > right) {
let s = str + ")"
generateParenthesisUtil(&result,s, n, left, right + 1)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment