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 :

  • 相关阅读:
    Docker(12)- docker run 命令详解
    adb 常用命令大全(7)- 其他实用功能
    adb 常用命令大全(6)- 模拟按键输入
    adb 常用命令大全(5)- 日志相关
    adb 常用命令大全(4)- 应用管理
    adb 常用命令大全(3)- 查看手机设备信息
    adb 常用命令大全(2)- 基础命令
    adb 常用命令大全(1)- 汇总
    Docker
    Docker(11)- docker ps 命令详解
  • 原文地址:https://www.cnblogs.com/forPrometheus-jun/p/10732436.html
Copyright © 2011-2022 走看看