Created
July 26, 2022 02:54
-
-
Save lucasrpb/191b54dc0edf75637295050a2cf651a8 to your computer and use it in GitHub Desktop.
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 java.util.concurrent.LinkedBlockingDeque | |
/* | |
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. | |
For example, given n = 3, a solution set is: | |
[ | |
"((()))", | |
"(()())", | |
"(())()", | |
"()(())", | |
"()()()" | |
] | |
*/ | |
object MatchingParens extends App { | |
var output = new LinkedBlockingDeque[String]() | |
def parens(left: Int, right: Int, str: String): Unit = { | |
// All pairs matched | |
if(left == 0 && right == 0){ | |
output.push(str) | |
} | |
// while there is open parent increment close number | |
if(left > 0){ | |
parens(left - 1, right + 1, str + "(") | |
} | |
// close open paren | |
if(right > 0){ | |
parens(left, right - 1, str + ")") | |
} | |
} | |
val n = 4 | |
// We start with the number of open paren and decrease down to 0 matching with closed ones | |
parens(n, 0, "") | |
println(output) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment