LeetCode第21题之Generate Parentheses(两种解法)

C++代码:
解法一(在LeetCode上运行效率高于解法二):

#include <vector>
#include <iostream>
#include <string>
using namespace std;

class Solution {
private:
    vector<string> res;
public: 
    //leftRemain保存还可以放左括号的数目,rightRemain保存还可以放右括号的数目
    void dfs(string state, int leftRemain, int rightRemain)
    {
        //这种情况括号不匹配
        if (leftRemain > rightRemain)
        {
            return;
        }
        if (0 == leftRemain && 0 == rightRemain)
        {
            res.push_back(state);
            return;
        }
        if (leftRemain > 0)
        {
            dfs(state + "(", leftRemain -1, rightRemain);
        }
        if (rightRemain >0 )
        {
            dfs(state + ")", leftRemain, rightRemain-1);
        }
    }
    vector<string> generateParenthesis(int n) {
        dfs("",n,n);
        return res;
    }
};

int main()
{
    Solution s;
    vector<string> r = s.generateParenthesis(3);
    for (vector<string>::iterator it = r.begin();it != r.end();++it)
    {
        cout<<*it<<endl;
    }
    return 0;
}

解法二:

#include <vector>
#include <iostream>
#include <string>
using namespace std;

class Solution {
private:
    //保存结果
    vector<string> res;
public:
    void fun(int deep, int n, int leftNum, int leftTotalNum, string s)
    {
        //如果左括号的总数大于n,则该字符串不可能满足要求
        if (leftTotalNum  > n)
        {
            return;
        }
        //如果到达最底层,则s一定满足题意。因为运行到这里时,leftTotalNum<=n,而leftNum>=0
        if (n*2 == deep)
        {
            res.push_back(s);
            return;
        }
        for (int i=0;i<2;++i)
        {
            if (0 == i)
            {
                //在deep+1的位置放左括号
                fun(deep+1, n, leftNum+1, leftTotalNum+1, s + "(");
            }
            else
            {
                //如果有剩余未匹配的左括号数,才能放右括号
                if (leftNum > 0)
                {
                    fun(deep+1, n, leftNum-1, leftTotalNum, s + ")");
                }
            }
        }
    }
    vector<string> generateParenthesis(int n) {
        //剩余未匹配的左括号数
        int leftNum = 0;
        //字符串中左括号总数
        int leftTotalNum =0;
        string s = "";
        fun(0, n, leftNum, leftTotalNum, s);
        return res;
    }
};

int main()
{
    Solution s;
    vector<string> r = s.generateParenthesis(3);
    for (vector<string>::iterator it = r.begin();it != r.end();++it)
    {
        cout<<*it<<endl;
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值