6 lines c++ 3~4 ms, super easy to understand

  • 18
    vector<string> result;
    void helper(string str, int left, int right){
        if(left == 0 && right == 0)  result.push_back(str);
        if(left!=0)                  helper(str+'(', left-1, right);
        if(right!=0 && right > left) helper(str+')', left, right-1);
    vector<string> generateParenthesis(int n) {
        return result;

  • 0
    This post is deleted!

  • 3

    The helper checks can be simplified:

    void helper(string str, int left, int right){
        if(left)         helper(str+'(', left-1, right);
        if(right > left) helper(str+')', left, right-1);
        if(!right)       result.push_back(str);

    I moved your first case to the end because it does happen at the end and because then readers will have already seen the right > left check when they see the !right check.

  • 0

    what is the complexity?

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.