码迷,mamicode.com
首页 > 其他好文 > 详细

22. Generate Parentheses

时间:2019-04-18 22:06:51      阅读:174      评论:0      收藏:0      [点我收藏+]

标签:sequence   write   ==   def   ber   position   重复项   cti   函数   

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 :

22. Generate Parentheses

标签:sequence   write   ==   def   ber   position   重复项   cti   函数   

原文地址:https://www.cnblogs.com/forPrometheus-jun/p/10732436.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!