leetcode128-generate-parentheses

题目描述

给出n对括号,请编写一个函数来生成所有的由n对括号组成的合法组合。
例如,给出n=3,解集为:
"((()))", "(()())", "(())()", "()(())", "()()()"

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:

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



示例1

输入

复制
1

输出

复制
["()"]
示例2

输入

复制
2

输出

复制
["(())","()()"]

class Solution {
public:
    /**
     *
     * @param n int整型
     * @return string字符串vector
     */
    void generateParenthesisAux(int n,int x ,int y,string s,vector<string> &ans){
        if (y==n)  ans.push_back(s);
        if (x<n) generateParenthesisAux(n, x+1, y,  s+"(", ans);
        if (x>y) generateParenthesisAux(n,  x, y+1, s+")", ans);
    }
    vector<string> generateParenthesis(int n) {
        // write code here
        vector <string> ans;
        generateParenthesisAux(n,0,0,"",ans);
        return ans;
    }
};

posted on 2020-08-01 11:08  滚雪球效应  阅读(238)  评论(0编辑  收藏  举报