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 :