[LeetCode]22. Generate Parentheses

Description

Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

Example

For example, given n = 3, a solution set is:

[
“((()))”,
“(()())”,
“(())()”,
“()(())”,
“()()()”
]

Discussion

这个题目是给定一个整数n,要求给出所有的括号匹配情况。考虑使用深度优先搜索来遍历所有的括号情况。需要注意的是从任意点往前看左括号的数目都不能小于右括号的数目,否则就会有一个单独的右括号没有匹配。

算法的时间复杂度为种类数,md不会算。

C++ Code

class Solution {
public:
    vector<string> generateParenthesis(int n) {
        vector<string> answer;
        dfs(0, 0, n, "", answer);
        return answer;
    }
    /**
    **运用dfs来遍历每种搭配。左括号的数量不可能小于右括号
    **leftNum:左括号数
    **rightNum:右括号数
    **predix:前面已有字符串
    **/
    void dfs(int leftNum, int rightNum, int n, string predix, vector<string> &answer)
    {
        if(leftNum == n && rightNum == n)
        {
            answer.push_back(predix);
        }
        //若左括号数量比右括号多,则下一个可以是左括号或右括号
        if(leftNum > rightNum)
        {
            if(leftNum < n)
                dfs(leftNum + 1, rightNum, n, predix + '(', answer);
            if(rightNum < n)
                dfs(leftNum, rightNum + 1, n, predix + ')', answer);
        }
        //若左括号数量和右括号一样,则下一个只能是左括号
        if(leftNum == rightNum)
        {
            if(leftNum < n)
                dfs(leftNum + 1, rightNum, n, predix + '(', answer);
        }
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值