-
Notifications
You must be signed in to change notification settings - Fork 0
/
22GenerateParentheses.swift
50 lines (45 loc) · 1.4 KB
/
22GenerateParentheses.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
/*
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
Exmaples:
Input: n = 3
Output: ["((()))","(()())","(())()","()(())","()()()"]
Input: n = 1
Output: ["()"]
*/
class Solution {
func generateParenthesis(_ n: Int) -> [String] {
var parenthesisArray: [String] = []
backtrack(parenthesisArray: &parenthesisArray, currentString: "", openIndex: 0, closeIndex: 0, maxIndex: n)
return parenthesisArray
}
private func backtrack(
parenthesisArray: inout [String],
currentString: String,
openIndex: Int,
closeIndex: Int,
maxIndex: Int
) {
guard currentString.count != maxIndex * 2 else {
parenthesisArray.append(currentString)
return
}
if openIndex < maxIndex {
backtrack(
parenthesisArray: &parenthesisArray,
currentString: currentString + "(",
openIndex: openIndex + 1,
closeIndex: closeIndex,
maxIndex: maxIndex
)
}
if closeIndex < openIndex {
backtrack(
parenthesisArray: &parenthesisArray,
currentString: currentString + ")",
openIndex: openIndex,
closeIndex: closeIndex + 1,
maxIndex: maxIndex
)
}
}
}