forked from NilaakashSingh/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
GenerateParentheses.swift
34 lines (28 loc) · 947 Bytes
/
GenerateParentheses.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
/**
* Question Link: https://leetcode.com/problems/generate-parentheses/
* Primary idea: Insert left and right parentheses and ensure they are valid
* Time Complexity: O(2^n), Space Complexity: O(n)
*
*/
class GenerateParentheses {
func generateParenthesis(_ n: Int) -> [String] {
guard n > 0 else {
return [String]()
}
var paths = [String](), path = ""
dfs(&paths, path, n, n)
return paths
}
private func dfs(_ paths: inout [String], _ path: String, _ leftRemaining: Int, _ rightRemaining: Int) {
if rightRemaining == 0 {
paths.append(path)
return
}
if leftRemaining > 0 {
dfs(&paths, path + "(", leftRemaining - 1, rightRemaining)
}
if rightRemaining > leftRemaining {
dfs(&paths, path + ")", leftRemaining, rightRemaining - 1)
}
}
}