首页 > 其他 > 详细

Leetcode generate-parentheses(生成括号, DFS)

时间:2020-04-27 00:37:14      阅读:82      评论:0      收藏:0      [点我收藏+]

题目描述

给出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();
            }
        }
    }
};

 

Leetcode generate-parentheses(生成括号, DFS)

原文:https://www.cnblogs.com/zl1991/p/12783710.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!