LeetCode #22 Generate Parentheses
LeetCode #22 Generate Parentheses
Question
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:
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]
Solution
Approach #1
class Solution {
func generateParenthesis(_ n: Int) -> [String] {
var results: [String] = []
func parenthesisStrings(_ str: String, _ open: Int, _ close: Int) {
if open == 0, close == 0 {
results.append(str)
return
}
if open > 0 {
parenthesisStrings(str + "(", open - 1, close)
}
if close > open {
parenthesisStrings(str + ")", open, close - 1)
}
}
parenthesisStrings("", n, n)
return results
}
}
转载请注明出处:http://www.cnblogs.com/silence-cnblogs/p/7065835.html