zoukankan      html  css  js  c++  java
  • [LeetCode] #22 Generate Parentheses

    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:

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

    本题是括号匹配输出,利用迭代输出。时间:3ms

    代码如下:

    class Solution {
    public:
        void unguarded_generate(vector<string> &result, string curr, int m, int n){
            if (m == 0 && n == 0){
                result.push_back(curr);
            }
            else{
                if (m != 0){
                    cout << curr << endl;
                    unguarded_generate(result, curr + "(", m - 1, n);
                }
                if (m < n && n != 0){
                    cout << curr << endl;
                    unguarded_generate(result, curr + ")", m, n - 1);
                }
            }
        }
    
        vector<string> generateParenthesis(int n) {
            vector<string> ret;
            if (n > 0){
                unguarded_generate(ret, string(), n, n);
            }
            return ret;
        }
    };
    “If you give someone a program, you will frustrate them for a day; if you teach them how to program, you will frustrate them for a lifetime.”
  • 相关阅读:
    爬虫项目数据解析方式
    数据分析
    爬虫项目代理操作和线程池爬取
    Python网络爬虫
    Django多表操作
    网络编程
    python中什么是元类
    Python面向对象中super用法与MRO机制
    mysql之pymysql
    mysql之索引原理
  • 原文地址:https://www.cnblogs.com/Scorpio989/p/4545075.html
Copyright © 2011-2022 走看看