leetcode_c++:Generate Parentheses(022)

来源:互联网 发布:c语言usleep函数 编辑:程序博客网 时间:2024/05/21 09:21

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 对括号的所有有效组合


DFS
O(2^n)


class Solution {private:    string tmp;    void dfs(vector<string> &v, int pos, int n, int used) {        if (pos == n * 2) {            cout << tmp << endl;            v.push_back(tmp);            return;        }        if (used < n) {            tmp.push_back('(');            dfs(v, pos + 1, n, used + 1);            tmp.pop_back();        }        if (used * 2 > pos) {            tmp.push_back(')');            dfs(v, pos + 1, n, used);            tmp.pop_back();        }    }public:    vector<string> generateParenthesis(int n) {        vector<string> res;        if (n == 0)            return res;        tmp = "";        dfs(res, 0, n, 0);        return res;    }};
0 0
原创粉丝点击