zoukankan      html  css  js  c++  java
  • Leetcode generate-parentheses(生成括号, DFS)

    题目描述

    给出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();
                }
            }
        }
    };
  • 相关阅读:
    筛选法 || POJ 1356 Prime Land
    搜索 || BFS || POJ 3278 Catch That Cow
    (素数筛) 找质数
    (map)后缀字符串
    字符串的进制
    (二进制枚举子集)买玩具
    (基础)01背包问题
    (基础)编辑距离
    (基础)最长公共字串
    最大子矩阵和
  • 原文地址:https://www.cnblogs.com/zl1991/p/12783710.html
Copyright © 2011-2022 走看看