22. 括号生成

2020-03-10  本文已影响0人  寂灭天骄小童鞋

https://leetcode-cn.com/problems/generate-parentheses/

var result = [String]()
func generateParenthesis(_ n: Int) -> [String] {
    backtrack(result, "", 0, 0, n)
    return result
}

func backtrack(_ arr: [String], _ curStr: String, _ leftCount: Int, _ rightCount: Int, _ n: Int) {
    if curStr.count == n * 2 {
        result.append(curStr)
        return
    }
    if leftCount < n {
        backtrack(arr, curStr + "(", leftCount + 1, rightCount, n)
    }
    if rightCount < leftCount {
        backtrack(arr, curStr + ")", leftCount, rightCount + 1, n)
    }
}
上一篇 下一篇

猜你喜欢

热点阅读