swift leetcode-22 Generate Parentheses

506 阅读1分钟

题目连接: https://leetcode.com/problems/generate-parentheses/description/

思路:

  • 归类是回溯,递归方法解决,确保(优先于),规定leftright分别对应左右括号, 先放置(,然后如果right < left,放置)。最后如果left == n(已全部放置,则放置最后一个)

Solution:

class Solution {
    func generateParenthesis(_ n: Int) -> [String] {
        func getIndex(_ res: inout [String], _ str: String, _ left: Int, _ right: Int){
            if left + right == 2 * n{
                res.append(str)
                return 
            }
            if left < n{
                let s = str + "("
                getIndex(&res,s,left + 1,right)
                if left > right{
                    let s = str + ")"
                    getIndex(&res,s,left,right + 1)
                }
            }else{
                let s = str + ")"
                getIndex(&res,s,left,right + 1)
            }
            
        }
        var res = [String]()
        var s = ""
        getIndex(&res,s,0,0)
        return res
    }
}