Generate Parentheses

来源:互联网 发布:车辆数据 编辑:程序博客网 时间:2024/06/07 06:04

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>res;        if(n==0) return res;        string solu;        helper(n,n,solu,res);        return res;    }    void helper(int lnum,int rnum,string solu,vector<string>&res){        if(lnum==0&&rnum==0){            res.push_back(solu);            return;        }else if(lnum==rnum){            string tmp=solu+'(';            helper(lnum-1,rnum,tmp,res);        }else{            if(lnum!=0){                string tmp=solu+'(';                helper(lnum-1,rnum,tmp,res);            }            if(rnum!=0){                string tmp2=solu+')';                helper(lnum,rnum-1,tmp2,res);            }        }    }};


0 0