Leetcode 22. Generate Parentheses

文章作者:Tyan
博客:noahsnail.com  |  CSDN  | 

1. Description

Generate Parentheses

2. Solution

class Solution {
public:
    vector generateParenthesis(int n) {
        vector result;
        push(0, 0, result, "", n, '(');
        return result;
    }
    
private:
    void push(int left, int right, vector& result, string s, const int n, char ch) {
        s += ch;
        if(ch == '(') {
            left++;
        }
        else {
            right++;
        }
        if(left > n || right > n || right > left) {
            return;
        }
        if(s.length() == 2 * n) {
            result.push_back(s);
            return;
        }
        push(left, right, result, s, n, '(');
        push(left, right, result, s, n, ')');
    }
};

Reference

  1. https://leetcode.com/problems/generate-parentheses/description/

你可能感兴趣的:(Leetcode 22. Generate Parentheses)