Accepted 3ms c++ solution use backtracking, easy understand.


  • -1
    class Solution {
    public:
        std::vector<std::string> generateParenthesis(int n) {
            std::vector<std::string> res;
            std::string str;
            generateParenthesis(res, str, 0, 0, n);
            return res;
        }
    private:
        void generateParenthesis(std::vector<std::string> &res, std::string str, int left, int right, int &n) {
            if (left + right == 2 * n) {
                res.push_back(str);
                return;
            }
            if (left < n)
                generateParenthesis(res, str + '(', left + 1, right, n);
            if (left > right)
                generateParenthesis(res, str + ')', left, right + 1, n);
        }
    };

Log in to reply
 

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