[Swift]LeetCode22. 括號生成 | Generate Parentheses
阿新 • • 發佈:2018-11-01
生成 ack nbsp tree dpa self. 一點 ons 添加
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:
[ "((()))", "(()())", "(())()", "()(())", "()()()" ]
給出 n 代表生成括號的對數,請你寫出一個函數,使其能夠生成所有可能的並且有效的括號組合。
例如,給出 n = 3,生成結果為:
[ "((()))", "(()())", "(())()", "()(())", "()()()" ]
【回溯法】 思路和算法
只有在我們知道序列仍然保持有效時才添加 ‘(‘
or ‘)‘
,而不是像方法一那樣每次添加。我們可以通過跟蹤到目前為止放置的左括號和右括號的數目來做到這一點,
如果我們還剩一個位置,我們可以開始放一個左括號。 如果它不超過左括號的數量,我們可以放一個右括號。
1 class Solution { 2 func generateParenthesis(_ n: Int) -> [String] { 3 var ans:[String] = [String]() 4 backtrack(&ans, "", 0, 0, n) 5 return ans 6 } 7 8 func backtrack(_ ans: inout [String], _ cur:String, _ open:Int, _ close:Int, _ max:Int) 9 { 10 if cur.count == max * 2 11 { 12 ans.append(cur) 13 return 14 } 15 if open < max16 { 17 backtrack(&ans, cur+"(", open+1, close, max) 18 } 19 if close < open 20 { 21 backtrack(&ans, cur+")", open, close+1, max) 22 } 23 } 24 }
【閉合數】思路
為了枚舉某些內容,我們通常希望將其表示為更容易計算的不相交子集的總和。
考慮有效括號序列 S
的閉包數:至少存在index> = 0
,使得 S[0], S[1], ..., S[2*index+1]
是有效的。 顯然,每個括號序列都有一個唯一的閉包號。 我們可以嘗試單獨列舉它們。
算法
對於每個閉合數 c
,我們知道起始和結束括號必定位於索引 0
和 2*c + 1
。然後兩者間的 2*c
個元素一定是有效序列,其余元素一定是有效序列。
1 class Solution { 2 func generateParenthesis(_ n: Int) -> [String] { 3 var ans:[String] = [String]() 4 if n == 0 5 { 6 ans.append("") 7 } 8 else 9 { 10 for c in 0..<n 11 { 12 for left in generateParenthesis(c) 13 { 14 for right in generateParenthesis(n-1-c) 15 { 16 ans.append("(" + left + ")" + right) 17 } 18 } 19 } 20 } 21 return ans 22 } 23 }
8ms
1 class Solution { 2 func generateParenthesis(_ n: Int) -> [String] { 3 var output: [String] = [] 4 5 handler(output: &output, n: n, left: 0, right: 0, text: "") 6 7 return output 8 } 9 10 func handler(output: inout [String], n: Int, left: Int, right: Int, text: String) { 11 // print("left: \(left), right: \(right)") 12 13 if(left == n && right == n) { 14 output.append(text) 15 return 16 } 17 18 if(left <= n && left > right) { 19 handler(output: &output, n: n, left: left, right: right + 1, text: text + ")") 20 } 21 22 if(left < n) { 23 handler(output: &output, n: n, left: left + 1, right: right, text: text + "(") 24 } 25 26 } 27 }
12ms
1 class Solution { 2 func generateParenthesis(_ n: Int) -> [String] { 3 var ss = [String]() 4 generate(ss: &ss, s: "", open: 0, close: 0, n: n) 5 return ss 6 } 7 8 private func generate(ss: inout [String], s: String, open: Int, close: Int, n: Int) { 9 if s.count == n * 2 && !s.isEmpty { 10 ss.append(s) 11 } 12 if open < n { 13 generate(ss: &ss, s: "\(s)(", open: open+1, close: close, n: n) 14 } 15 if close < open { 16 generate(ss: &ss, s: "\(s))", open: open, close: close+1, n: n) 17 } 18 } 19 }
12ms
1 class Solution { 2 func generateParenthesis(_ n: Int) -> [String] { 3 guard n > 0 else { 4 return [] 5 } 6 var result = [String]() 7 8 dfs(left: 0, right: 0, buffer: "", result: &result, n: n) 9 10 return result 11 } 12 13 func dfs(left: Int, right: Int, buffer: String, result: inout [String], n: Int) { 14 if left == n && right == n { 15 result.append(buffer) 16 return 17 } 18 19 if left < n { 20 dfs(left: left + 1, right: right, buffer: buffer + "(", result: &result, n: n) 21 } 22 23 if left > right { 24 dfs(left: left, right: right + 1, buffer: buffer + ")", result: &result, n: n) 25 } 26 } 27 }
20ms
1 class Solution { 2 func generateParenthesis(_ n: Int) -> [String] {//閉合數 3 return generateBracket(n) 4 } 5 6 func generateBracket(_ n: Int) -> [String] { 7 if n <= 0 { 8 return [""] 9 } 10 11 12 var bracket : [String] = [] 13 14 for idx in 0..<n { 15 for left in generateBracket(idx) { 16 for right in generateBracket(n-idx-1) { 17 bracket.append("(\(left))\(right)") 18 } 19 } 20 } 21 22 return bracket 23 } 24 }
24ms
1 class Solution { 2 func generateParenthesis(_ n: Int) -> [String] { 3 if n == 0 {return []} 4 return dfs("", n, n) 5 } 6 7 //遍歷葉子節點 8 func dfs(_ head:String, _ left:Int, _ right:Int) -> [String] { 9 if left == 0 && right == 0 { 10 return [head] 11 } 12 var res = [String]() 13 if left > 0 { 14 res = res + dfs(head + "(", left-1, right) 15 } 16 if right > left { 17 res = res + dfs(head + ")", left, right-1) 18 } 19 return res 20 } 21 }
44ms
1 class Solution { 2 enum Paren: String { 3 case o = "(" 4 case c = ")" 5 } 6 7 class TreeNode { 8 let val: Paren 9 var left: TreeNode? 10 var right: TreeNode? 11 12 init(val: Paren) { 13 self.val = val 14 } 15 16 func treeValues() -> [String] { 17 // DFS walk the tree multiple times to print out the tree 18 guard (self.left != nil) || (self.right != nil) else { 19 return [self.val.rawValue] 20 } 21 22 var res = [String]() 23 for node in [self.left, self.right] { 24 if let node = node { 25 for s in node.treeValues() { 26 res.append(self.val.rawValue + s) 27 } 28 } 29 } 30 return res 31 } 32 } 33 34 func populateTree(root: TreeNode, maxOpenParens: Int, availOpenParens: Int, availClosedParens: Int) { 35 // Implement a BST 36 if availOpenParens > 0 { 37 root.left = TreeNode(val: Paren.o) 38 populateTree(root: root.left!, maxOpenParens: maxOpenParens, availOpenParens: availOpenParens - 1, availClosedParens: availClosedParens + 1) 39 } 40 if availClosedParens > 0 { 41 root.right = TreeNode(val: Paren.c) 42 populateTree(root: root.right!, maxOpenParens: maxOpenParens, availOpenParens: availOpenParens, availClosedParens: availClosedParens - 1) 43 } 44 } 45 46 func generateParenthesis(_ n: Int) -> [String] { 47 let root = TreeNode(val: Paren.o) 48 populateTree(root: root, maxOpenParens: n, availOpenParens: n - 1, availClosedParens: 1) 49 return root.treeValues() 50 } 51 }
[Swift]LeetCode22. 括號生成 | Generate Parentheses