LeetCode 22. Generate Parentheses

来源:互联网 发布:php分页类代码 编辑:程序博客网 时间:2024/06/18 05:51

22. Generate Parentheses

Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

For example, given n = 3, a solution set is:

[
“((()))”,
“(()())”,
“(())()”,
“()(())”,
“()()()”
]

题目内容:
题目给出一个正整数n,让我们返回所有包含n对括号的组合。

解题思路:
方法1:
对于一个正整数n,我们用p[n]表示由n对括号组成的字符串集合。
假如n=3,那么

p[3]=p[1]×p[2]p[2]×p[1]{"("+p[2]+")"} (× )

也就是说,我们可以把p[n]集合的组成分成两大部分:
1. 将p[n]分成左右两部分,假如左半部分长度为left,右半部分有right,那么p[n]就可以由p[left]和p[right]拼起来,注意要去重。
2. 将一对括号用在两边,那么里面的部分则由p[n-1]组成。
所以,其实这是一种动态规划的方法。

方法2:
在我们在用这些括号来构建一个字符串的过程,相当于在构建一棵树,每一个字符串用一个节点表示,我们可以在这个字符串尾部加入’(‘或者’)’,相当于给当前节点加上2个子节点。那么对于一个节点,当我们加上一个’(‘或者’)’之后是否合法的这个问题,我们可以给每个节点用一个available变量来表示可以在当前字符串结尾加上’)’字符的数量。当一个子节点是由父节点字符串尾部加上’(‘得到的,那么available加1,否则减1。那么到最后,我们可以找出所有长度为2*n的合法的字符串。

代码:
方法1:

class Solution {public:    vector<string> generateParenthesis(int n) {        map<string, bool> str2exist;        vector<vector<string>> num2p;        num2p.push_back(vector<string>({"()"}));        for (int i = 2; i <= n; i++) {            vector<string> temp;            for (int j = 0; j < num2p[i - 2].size(); j++) {                string str = '(' + num2p[i - 2][j] + ')';                temp.push_back(str);                str2exist[str] = true;            }            for (int left = 1; left < i; left++) {                int right = i - left;                for (int m = 0; m < num2p[left - 1].size(); m++) {                    for (int j = 0; j < num2p[right - 1].size(); j++) {                        string str = num2p[left - 1][m] + num2p[right - 1][j];                        if (str2exist.find(str) == str2exist.end()) {                            str2exist[str] = true;                            temp.push_back(str);                        }                    }                }            }            num2p.push_back(temp);        }        return num2p[n - 1];    }};

方法2:

struct state {    int available;    string str;    state(int a, string s) : available(a), str(s) {}};class Solution {public:    vector<string> generateParenthesis(int n) {        queue<state*> q;        q.push(new state(1, "("));        int length = 2 * n;        while (true) {            state* s = q.front();            if (s->str.size() == length) break;            if (s->available > 0) {                q.push(new state(s->available - 1, s->str + ')'));            }            if (length - s->str.size() >= s->available) {                q.push(new state(s->available + 1, s->str + '('));            }            delete s;            q.pop();        }        vector<string> result;        while (!q.empty()) {            state* s = q.front();            q.pop();            if (s->available == 0) {                result.push_back(s->str);            }            delete s;        }        return result;    }};
原创粉丝点击