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 :

  • 相关阅读:
    Promise链式调用 终止或取消
    uni-app input text-indent失效解决
    从浏览器输入url到显示页面的过程 (前端面试题)
    node.js切换多个版本
    防抖和节流
    vue子组件与子组件之前传值-----最简单办法
    Element源码---初识框架
    vue中父级与子组件生命周期的先后顺序
    vscode快捷键,让你脱离鼠标,敲代码嗖嗖的
    NHibernate代码监视
  • 原文地址:https://www.cnblogs.com/forPrometheus-jun/p/10732436.html
Copyright © 2011-2022 走看看