Leetcode每日一题:22.generate-parentheses(括号生成)

在这里插入图片描述
本题分别采用两种方法:暴力法(set+vector) 以及 dfs(vector)
在这里插入图片描述

vector<string> generateParenthesis(int n) {
    set<string> resSet;//利用set的去重 将所有的可能放入set中 然后转换成vector
    vector<string> res;

    //boundary condition
    if (n == 0)
        return res;
    resSet.insert("()");
    if (n == 1)
    {
        res.push_back("()");
        return res;
    }

    // !recursion
    for (int i = 2; i <= n; i++)
    {
        set<string> resTemp = resSet;
        resSet.clear();
        for (auto s : resTemp)
        {
            //brackets is between the s  挨个插括号 每个位置都插一遍
            for (int j = 0; j < s.size(); j++)
            {
                string left = s.substr(0, j);
                string right = s.substr(j);
                resSet.insert(left + "()" + right);
            }
            //brackets is out of the s
            resSet.insert("(" + s + ")");
        }
    }
    //take the string in the vector
    for (auto s : resSet)
    {
        res.push_back(s);
    }
    return res;
    }

在这里插入图片描述
明显的比较出DFS在时间这方面是多么高效

void DFS(vector<string> &vs, string curstr, int left, int right) //remain left '(' and right ')'
{
    //boundary condition
    if (left > right)//左括号剩余数量不能多余右括号
        return;
    if (left < 0 || right < 0)
        return;
    if (left == 0 && right == 0)
    {
        vs.push_back(curstr);
        return;
    }

    if (left > 0) //if the left is remained ,continue traverse 
        DFS(vs, curstr + '(', left - 1, right);
    if (right > 0)//if the right is remained ,continue traverse
        DFS(vs, curstr + ')', left, right - 1);
}

vector<string> generateParenthesis(int n)
{
    vector<string> res;

    //boundary condition
    if (n == 0)
        return res;
    if (n == 1)
    {
        res.push_back("()");
        return res;
    }

    // DFS
    DFS(res, "", n, n);//the number of '(' and ')' are both n
    return res;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值