[LeetCode]22. Generate Parentheses

  "给出n对括号的所有匹配情况"

Posted by Stephen.Ri on October 8, 2017

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);
        }
    }
};