题目描述

给出n对括号,请编写一个函数来生成所有的由n对括号组成的合法组合。
例如,给出n=3,解集为:
"((()))", "(()())", "(())()", "()(())", "()()()"
 

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:

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

思路:与按键盘给数字生成字母的思路一致,用dfs,注意判断,l==n&&r==n的时候才push,l<n的时候可以加左括号,r<l的时候可以加右括号
class Solution {
public:
    vector<string> generateParenthesis(int n) {
        vector<string> res;
        string out;
        DFS(n,0,0,out,res);
        return res;
    }
    void DFS(int n,int l,int r,string &out,vector<string> &res)
    {
        if(l==n&&r==n)
        {
            res.push_back(out);
            return;
        }
        else
        {
            if(l<n)
            {
                out.push_back('(');
                DFS(n,l+1,r,out,res);
                out.pop_back();
            }
            if(l>r)
            {
                out.push_back(')');
                DFS(n,l,r+1,out,res);
                out.pop_back();
            }
        }
    }
};

 

相关文章:

  • 2021-12-11
  • 2022-12-23
  • 2021-09-17
  • 2022-02-18
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-08-03
猜你喜欢
  • 2022-01-12
  • 2021-05-16
  • 2021-08-15
  • 2021-08-28
  • 2021-06-25
  • 2021-08-22
  • 2021-08-22
相关资源
相似解决方案