Created
January 19, 2020 12:40
-
-
Save spurscho/810f0fb7c23dde39584e0c7d5d5899f7 to your computer and use it in GitHub Desktop.
22. Generate Parentheses
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
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