leetcode刷题笔记二十二 括号生成 Scala版本
源地址:22. 括号生成
问题描述:
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:
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]
代码补充:
//方法一:DFS
object Solution {
var ans = List[String]()
def generateParenthesis(n: Int): List[String] = {
//当n=0时,返回空列表
if (n == 0) return List()
//当n!=0时,共出现n个左括号,n个右括号
var left = n
var right = n
ans = List[String]()
var tempAns = ""
dfs(left, right, "")
return ans
}
def dfs(left:Int, right:Int, tempAns:String):Unit={
//若右括号比左括号多,这种情况不匹配,直接返回
if (left > right) return
//若左、右括号匹配,且左、右括号均以完成n次,将这一次结果加
//入答案
if ( left == 0 && right == 0 ) {
ans = ans :+ tempAns
return
}
//左边未进行完,进行一次左括号
if (left != 0) dfs(left-1, right, tempAns+'(' )
//右边未进行完,进行一次右括号
if (right != 0) dfs(left, right-1, tempAns+')')
}
}
//方法二:动态规划
//对于n对括号,最外侧肯定有一对括号l,剩下n-1对括号或位于l内侧,或者位于l外侧
//初始状态:F(0) = 0
//状态转换:F(n) = "(" + F(i) + ")" + F(j),其中0 <= i,j <= n-1 且 i+j = n-1
object Solution {
def generateParenthesis(n: Int): List[String] = {
var ans = List[String]()
//将F(0)视为空串
if (n == 0) ans = ans :+ ""
//需进行n-1次匹配
for(i <- 0 until n){
//括号内
val left = generateParenthesis(i)
//括号外
val right = generateParenthesis(n-1-i)
for (elemL <- left){
for (elemR <- right){
println("i: " + i)
println("j: " + (n-1-i).toString)
println("left: "+left)
println("right: "+right)
ans = ans :+ ("(" + elemL + ")" + elemR )
}
}
}
return ans
}
}