zoukankan      html  css  js  c++  java
  • 22. Generate Parentheses

    description:

    Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
    Note:

    Example:

    For example, given n = 3, a solution set is:
    
    [
      "((()))",
      "(()())",
      "(())()",
      "()(())",
      "()()()"
    ]
    

    my answer:

    感恩

    列出所有结果的题优先考虑迭代Recursion
    每找到一个左括号,就在其后面加一个完整的括号,最后再在开头加一个(),就形成了所有的情况,需要注意的是,有时候会出现重复的情况,所以我们用set数据结构,好处是如果遇到重复项,不会加入到结果中,最后我们再把set转为vector即可,

    n=1:    ()
    n=2:    (())    ()()
    n=3:    (()())    ((()))    ()(())    (())()    ()()() 
    

    大佬的answer:

    class Solution {
    public:
        vector<string> generateParenthesis(int n) {
            set<string> t;
            if (n == 0) t.insert("");//迭代的函数中必须有终止条件
            else {
                vector<string> pre = generateParenthesis(n - 1);
                for (auto a : pre) {
                    for (int i = 0; i < a.size(); ++i) {
                        if (a[i] == '(') {
                            a.insert(a.begin() + i + 1, '(');
                            a.insert(a.begin() + i + 2, ')');
                            t.insert(a);
                            a.erase(a.begin() + i + 1, a.begin() + i + 3);//attention the rank is [first,last)
                        }
                    }
                    t.insert("()" + a);
                }
            }
            return vector<string>(t.begin(), t.end());
        }
    };
    

    relative point get√:

    std::string::erase

    • sequence (1)

    string& erase (size_t pos = 0, size_t len = npos);

    Erases the portion of the string value that begins at the character position pos and spans len characters (or until the end of the string, if either the content is too short or if len is string::npos.
    Notice that the default argument erases all characters in the string (like member function clear).
    
    • character (2)

    iterator erase (iterator p);

    Erases the character pointed by p.    
    
    • range (3)

    iterator erase (iterator first, iterator last);

    Erases the sequence of characters in the range [first,last).
    

    Erase characters from string
    Erases part of the string, reducing its length:

    hint :

  • 相关阅读:
    Go语言学习之1 基本概念、环境搭建、第一个Go程序
    go环境搭建
    go 圣经阅读笔记之-入门
    RabbitMQ
    图片选择并使用base64展示
    关于c# hashtable的一个注意点
    js image to base64 摘录
    linq to sql 获取sql与参数添加到日志中
    时钟的实现
    无限级菜单的实现
  • 原文地址:https://www.cnblogs.com/forPrometheus-jun/p/10732436.html
Copyright © 2011-2022 走看看