Generate Parentheses--LeetCode

1.题目

Generate Parentheses

Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
For example, given n = 3, a solution set is:
[
“((()))”,
“(()())”,
“(())()”,
“()(())”,
“()()()”
]

2.题意

给定 n 对括号, 编写一个函数来生成格式正确的括号的所有组合。

3.分析

考虑递归求解
字符串只有’(‘和’)’两种字符,而且最终结果必定是3个’(‘,3个’)’
定义变量left和right表示左右括号的剩余个数
分为3种情况
1)left>right
即出现’)(‘这样的非法串,直接返回,不继续处理
2)left和right都为0
则此时生成的字符串已有n个左括号和n个右括号
且字符串合法,则存入结果中后返回
3)以上两种情况都不满足,
若left>0,则调用递归函数,注意left-1
若right>0,也调用递归函数,注意right-1

4.代码

1)分析中的代码实现

class Solution {
public:
    vector<string> generateParenthesis(int n) {
        vector<string> result;

        generateParenthesisDFS(result, n, n, "");

        return result;
    }

    void generateParenthesisDFS(vector<string> &result, int left, int right, string str){
        if(left < 0 || right <0 || left > right)
            return;

        if(left == 0 && right == 0)
        {
            result.push_back(str);
            return;
        }
        else
        {
            // if(left > 0)
                generateParenthesisDFS(result, left - 1, right, str + '(');
            // if(right > 0)
                generateParenthesisDFS(result, left, right - 1, str + ')');
        }

        return;
    }
};

2)思路与1类似,注意不要遗漏str.size() == n * 2
第2步的判断right < left不要写错

class Solution {
public:
    vector<string> generateParenthesis(int n) {
        vector<string> result;
        string str;

        generateParenthesisDFS(result, n, 0, 0, str);

        return result;
    }

    void generateParenthesisDFS(vector<string> &result, int n, int left, int right, string &str){
        if(left < n)
        {
            str.push_back('(');
            generateParenthesisDFS(result, n, left + 1, right, str);
            str.pop_back();
        }

        if(right < left)
        {
            str.push_back(')');
            generateParenthesisDFS(result, n, left, right + 1, str);
            str.pop_back();
        }

        if(str.size() == n * 2)
            result.push_back(str);

        return;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值