首页 > 代码库 > Leetcode--Generate Parentheses

Leetcode--Generate Parentheses

Problem Description:

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:

"((()))", "(()())", "(())()", "()(())", "()()()"

分析:按照题目意思,输入n,找出所有包含n个括号对的合法序列,自己想了半天没有什么思路,然后搜索了一下看到一条准则:即出现的“)”数目小于等于出现的“(”数目即可,因此直接利用DFS,即可得到所有序列。具体代码如下:

class Solution {
public:
    vector<string> res;

    void dfs(int n,int left,int right, string str)
    {
        if(left==right&&left==n)
        {
            res.push_back(str);
            return;
        }

        if(left<right||left>n)
            return;
        else
        {
            str+='(';
            dfs(n,left+1,right,str);
            str=str.substr(0,str.size()-1);

            str+=')';
            dfs(n,left,right+1,str);
            str=str.substr(0,str.size()-1);
        }

    }

    vector<string> generateParenthesis(int n) {
        if(n<=0)
            return res;
        string s="";
        dfs(n,0,0,s);
        return res;
    }
};