[LeetCode] 22. Generate Parentheses
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:
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]Analyse:
Solution:
class Solution {
func generateParenthesis(_ n: Int) -> [String] {
var output: [String] = [];
self.helper(open:n, close:0, output: &output, text:"")
return output;
}
func helper(open: Int, close:Int, output: inout [String], text: String) {
if (open > 0) {
self.helper(open: open - 1, close: close + 1, output: &output, text:text+"(")
}
if (close > 0) {
self.helper(open: open, close: close - 1, output: &output, text:text+")")
}
if(open == 0 && close == 0) {
output.append(text);
}
}
}Solution 2:
Last updated