1. 程式人生 > >leetCode 22. 括號生成(swift)

leetCode 22. 括號生成(swift)

給出 n 代表生成括號的對數,請你寫出一個函式,使其能夠生成所有可能的並且有效的括號組合。

例如,給出 =3,生成結果為:

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

分析:本題是在字串的分類裡面,但實際用的是回溯演算法。在回憶之前回溯演算法題的解法時,發覺回溯跟dfs方式是一樣的,不知道他們區別是什麼,就在網上搜了一下。

"Backtracking is a more general purpose algorithm.

Depth-First search is a specific form of backtracking related to searching tree structures. From Wikipedia:

One starts at the root (selecting some node as the root in the graph case) and explores as far as possible along each branch before backtracking. It uses backtracking as part of its means of working with a tree, but is limited to a tree structure.

Backtracking, though, can be used on any type of structure where portions of the domain can be eliminated - whether or not it is a logical tree. The Wiki example uses a chessboard and a specific problem - you can look at a specific move, and eliminate it, then backtrack to the next possible move, eliminate it, etc."

這是stackOverflow上面的一個回答,大致意思是一種可以通用的演算法,而dfs是回溯演算法在樹形結構的一種特殊用法。恩。。大概瞭解了一些。。

之前的回溯題目解法一般是陣列座標的回溯運動,這是第一次用到字串上,它的過程和邊界也比較有意思。上網搜了解法,理清了回溯過程,寫成swift提交上去,通過。

class Solution {
    func generateParenthesis(_ n: Int) -> [String] {

        var res = [String].init()
        dfs("", &res, n, 0, 0);
        return res;
    }
    func dfs(_ cur:String ,_ res:inout [String], _ n:Int, _ left:Int, _ right:Int) {

        if right == n {
            res.append(cur)
        }
        if left < n {
            dfs(cur+"(", &res, n, left+1, right);
        }
        if right < left {
            dfs(cur+")", &res, n, left, right+1);
        }
    }
}

反思:回溯的形式還是很多,條件寫起來也不太容易,還需要多練習。