swift leetcode-22 Generate Parentheses

本文介绍了一种使用回溯算法解决生成括号问题的方法。通过递归方式,确保左括号优先于右括号出现,并在适当位置放置右括号以保持平衡。最终实现了生成所有可能的括号组合。

题目连接: 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
    }
}
复制代码

转载于:https://juejin.im/post/5b3f9f106fb9a04fbb1102af

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值