22.leetcode Generate Parentheses(medium)[函数递归遍历]

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:
    void getResult(int left,int right,string s,vector &result)
    {
        if(left == 0 &&right == 0)
             result.push_back(s);
        if(left>0)
             getResult(left-1,right,s+'(',result);
        if(right>0&&left generateParenthesis(int n) {
        //因为最后要求括号成对出现,所以右括号添加的时候必须左括号小于右括号才可以
        vector result;
        if(n==0) return result;
        string s;
        getResult(n,n,s,result);
        return result;
    }
};


你可能感兴趣的:(编程)