LeetCode 22. Generate Parentheses

本文介绍了一种使用深度优先搜索(DFS)结合剪枝策略来解决括号生成问题的算法。该算法通过递归地在字符串中添加左括号和右括号,并在满足条件时将合法的括号组合加入结果集,最终返回所有可能的有效括号组合。

问题

https://leetcode.com/problems/generate-parentheses/

解法

dfs + 剪枝

class Solution {
public:
    void search(vector<string>& res, char * s, int lNum, int depth, int n)
    {
        if (depth ==n)
        {
            if (lNum == 0)
                res.push_back(string(s));
            return;
        }

        // '('
        s[depth] = '(';
        if (lNum+1 <= (n-1-depth))
            search(res, s, lNum+1, depth+1, n);
        s[depth] = ')';
        if (lNum-1 >= 0)
            search(res, s, lNum-1, depth+1, n);
    }
    vector<string> generateParenthesis(int n) {
        vector<string> ret;
        if (n==0)
            return ret;
        char s[2*n+1];
        s[2*n] = 0;
        search(ret, s, 0, 0, 2*n);
        return ret;
    }
};
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值