[Swift]LeetCode22. 括號生成 | Generate Parentheses

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-pleksnzr-me.html 
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html

Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.node

For example, given n = 3, a solution set is:git

[
  "((()))",
  "(()())",
  "(())()",
  "()(())",
  "()()()"
]

給出 n 表明生成括號的對數,請你寫出一個函數,使其可以生成全部可能的而且有效的括號組合。github

例如,給出 = 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 < max
16         {
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 }

【閉合數】思路

爲了枚舉某些內容,咱們一般但願將其表示爲更容易計算的不相交子集的總和。app

考慮有效括號序列 S 的閉包數:至少存在index> = 0,使得 S[0], S[1], ..., S[2*index+1]是有效的。 顯然,每一個括號序列都有一個惟一的閉包號。 咱們能夠嘗試單獨列舉它們。函數

算法spa

對於每一個閉合數 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 }
相關文章
相關標籤/搜索