forked from yuyongwei/Algorithms-In-Swift
-
Notifications
You must be signed in to change notification settings - Fork 1
/
generateParentheses.swift
106 lines (82 loc) · 2.19 KB
/
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
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
/*
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:
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]
https://leetcode.com/problems/generate-parentheses/
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* public var val: String
* public var left: TreeNode?
* public var right: TreeNode?
* public init(_ val: String) {
* self.val = val
* self.left = nil
* self.right = nil
* }
* }
*/
class Solution {
public class PNode {
public var val: String
public var left: PNode?
public var right: PNode?
public init(_ val: String) {
self.val = val
self.left = nil
self.right = nil
}
}
var result = [String]()
func generateParenthesis(_ n: Int) -> [String] {
guard n > 0 else { return [""] }
let root = PNode("(")
construct(root, n-1, n)
dfs(root, "")
return result
}
func dfs(_ node: PNode, _ path: String) {
var p = path
p.append(node.val)
if node.left == nil && node.right == nil { result.append(p) }
if let left = node.left {
dfs(left, p)
}
if let right = node.right {
dfs(right, p)
}
}
func construct(_ node: PNode, _ leftNum: Int, _ rightNum: Int) {
if leftNum == 0 && rightNum == 0 { return }
if node.val == "(" {
if leftNum > 0 {
let l = PNode("(")
node.left = l
construct(l, leftNum-1, rightNum)
}
if rightNum > 0 {
let r = PNode(")")
node.right = r
construct(r, leftNum, rightNum-1)
}
} else {
if rightNum > leftNum {
let r = PNode(")")
node.right = r
construct(r, leftNum, rightNum-1)
}
if leftNum > 0 {
let l = PNode("(")
node.left = l
construct(l, leftNum-1, rightNum)
}
}
}
}