4ms C++ solution with recursion


  • 0
    D
    class Solution {
    public:
        void parenthesis_helper(int left, int right, string* ans, vector<string>* res) {
            if (left < 0 || right < left) { return; }
            if (left == 0 && right == 0) {
                res->emplace_back(*ans);
                return;
            }
            if (left > 0) {
                ans->push_back('(');
                parenthesis_helper(left - 1, right, ans, res);
                ans->pop_back();
            }
            if (right > 0) {
                ans->push_back(')');
                parenthesis_helper(left, right - 1, ans, res);
                ans->pop_back();
            }
        }
        vector<string> generateParenthesis(int n) {
            if (n == 0) { return vector<string>{}; }
            string ans;
            vector<string> result;
            parenthesis_helper(n, n, &ans, &result);
            return result;
        }
    };

Log in to reply
 

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