-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathContents.swift
66 lines (53 loc) · 1.38 KB
/
Contents.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
/*
https://leetcode.com/problems/generate-parentheses/
22. Generate Parentheses
Medium
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:
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]
*/
import Foundation
class Solution {
func generateParenthesis(_ n: Int) -> [String] {
if n == 0 {return []}
var result: [String] = []
helper(0, left: n, right: n, "", &result)
return result
}
func helper(_ index: Int, left: Int, right: Int, _ carry: String, _ result: inout [String]) {
if right == 0 {
result.append(carry)
}
if left > 0 {
helper(index + 1, left: left - 1, right: right, carry + "(", &result)
}
if (right > left) {
helper(index + 1, left: left, right: right - 1, carry + ")", &result)
}
}
}
import Foundation
import XCTest
class SolutionTests: XCTestCase {
var solution: Solution!
override func setUp() {
super.setUp()
solution = Solution()
}
func testLeetcodeExample1() {
XCTAssertEqual(solution.generateParenthesis(3), [
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
])
}
}
SolutionTests.defaultTestSuite.run()