clueless coding // TODO: be smarter

LeetCode Generate Parentheses: CPP Solution



TL;DR Code Solution


void generate(vector<string>& result, string current, int open, int closed) {
    if (open == 0 && closed == 0) {
        result.push_back(current);
        return;
    }

    if (open > 0) {
        generate(result, current + "(", open - 1, closed);
    }
    if (closed > open) {
        generate(result, current + ")", open, closed - 1);
    }
}

vector<string> generateParenthesis(int n) {
    vector<string> result;
    if (n > 0) {
        generate(result, "", n, n);
    }
    return result;
}