Generate Parentheses (括号匹配)【leetcode】

来源:互联网 发布:io 域名 编辑:程序博客网 时间:2024/06/05 05:51

题目: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个,右括号个数小于等于左括号。


char str[10000];vector<string>ll;class Solution {public:    vector<string> generateParenthesis(int n) {        ll.clear();        hehe(0,n*2,0,0);        return ll;    }        void hehe(int i,int n,int leftnum,int rightnum)    {        if(i==n)        {            str[n]='\0';            string temp;            temp=str;            ll.push_back(temp);            return;        }        if(leftnum+1<=n/2)        {            str[i]='(';            hehe(i+1,n,leftnum+1,rightnum);        }        if(leftnum>rightnum)        {            str[i]=')';            hehe(i+1,n,leftnum,rightnum+1);        }            }};


原创粉丝点击