[LeetCode] 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:

"((()))", "(()())", "(())()", "()(())", "()()()"

class Solution {
public:
    vector<string> generateParenthesis(int n) {
        vector<string> list;
        
        stack<string> stack1 ;
        stack<int> vaStack1;
        stack1.push("(");
        vaStack1.push(0);//存储右括号的数量
        
        while(stack1.size()!=0){
            
            string s = stack1.top();
            int v = vaStack1.top();//v是右括号的数量
            stack1.pop();
            vaStack1.pop();
            if(s.size()==n*2){
                list.push_back(s);
                continue;
            } 
            if(s.size()-v<n){//左括号的数量小于n,给s后面补左括号
                stack1.push(s+"(");
                vaStack1.push(v);
            }
            if(2*v<s.size()){//缺右括号,给s后面补左括号
               stack1.push(s+")");
               vaStack1.push(v+1);
            }
        }
     return list;
    }
};
posted @ 2014-07-25 08:21  Xylophone  Views(105)  Comments(0Edit  收藏  举报