22. Generate Parentheses

来源:互联网 发布:mac 涂层脱落 编辑:程序博客网 时间:2024/06/08 17:32

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:

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

求出所以可能的括号对
递归
The idea is intuitive. Use two integers to count the remaining left parenthesis (n) and the right parenthesis (m) to be added. At each function call add a left parenthesis if n >0 and add a right parenthesis if m>0. Append the result and terminate recursive calls when both m and n are zero.

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); }    }};
0 0
原创粉丝点击