LeetCode 22 Generate Parentheses

来源:互联网 发布:linux程序设计pdf下载 编辑:程序博客网 时间:2024/05/01 17:00

题意:

用n组小括号,生成所有满足括号匹配的序列。


思路:

我用了比较粗暴的方式,用set不断迭代答案,每次迭代使得括号组数+1直到n为止。

还有一种方法是dfs构造,因为长度已经确定,所以每个位置要么放(要么放),利用前缀和维护括号匹配即可。


代码:

class Solution {public:    vector <string> generateParenthesis(int n) {        set <string> tmp{""};        while (n--) {            tmp = grow(tmp);        }        vector <string> ans;        for (auto it : tmp) {            ans.push_back(it);        }        return ans;    }private:    set <string> grow(set <string> &fa) {        set <string> son;        for (auto it : fa) {            son.insert("(" + it + ")");            for (int i = 0; i < it.size(); ++i) {                son.insert(it.substr(0, i + 1) + "()" + it.substr(i + 1, it.size() - i - 1));            }        }        return son;    }};


0 0
原创粉丝点击