Generate Parentheses

来源:互联网 发布:淘宝助理订单下载 编辑:程序博客网 时间:2024/06/08 10:01

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:

“((()))”, “(()())”, “(())()”, “()(())”, “()()()”

解:
其实正确的括号就是正确的出栈入栈顺序。假设出栈是”)” 入栈是”(“,枚举所有的出栈入栈的操作即得到所有的可能

class Solution {public:    vector<string> res;    vector<string> generateParenthesis(int n) {        generateParenthesis(n,"",stack<int>());        return res;    }    void generateParenthesis(int n,string s,stack<int> st) {        if(n==0)        {            while(!st.empty())            {                s=s+")";                st.pop();            }            res.push_back(s);            return ;        }        if(st.empty())        {            st.push(1);            generateParenthesis(n-1,s+"(",st);        }        else        {            st.push(1);            generateParenthesis(n-1,s+"(",st);            st.pop();            st.pop();            generateParenthesis(n,s+")",st);        }    }};

但其实并不非要有一个栈,我们所需要的只是当时栈中所剩元素的个数以及剩余没油入栈的元素个数,因此只需要两个计数器就可以。

class Solution {public:    vector<string> generateParenthesis(int n) {        vector<string> res;        addingpar(res, "", n, 0);        return res;    }    void addingpar(vector<string> &v, string str, int n, int m){        if(n==0 && m==0) {            v.push_back(str);            return;        }        if(m > 0){ addingpar(v, str+")", n, m-1); }        if(n > 0){ addingpar(v, str+"(", n-1, m+1); }    }};

看到评论区还有用DP做的,也贴上来好了
DP. First consider how to get the result f(n) from previous result f(0)…f(n-1). Actually, the result f(n) will be put an extra () pair to f(n-1). Let the “(” always at the first position, to produce a valid result, we can only put “)” in a way that there will be i pairs () inside the extra () and n - 1 - i pairs () outside the extra pair.

Let us consider an example to get clear view:

f(0): “”

f(1): “(“f(0)”)”

f(2): “(“f(0)”)”f(1), “(“f(1)”)”

f(3): “(“f(0)”)”f(2), “(“f(1)”)”f(1), “(“f(2)”)”

So f(n) = “(“f(0)”)”f(n-1) , “(“f(1)”)”f(n-2) “(“f(2)”)”f(n-3) … “(“f(i)”)”f(n-1-i) … “(f(n-1)”)”

0 0
原创粉丝点击