C++ solution by using DFS, easy to understand, 4ms.


  • 0
    Z
    void generateParenthesisRecursive(int left, int right, string cur, vector<string> &svec)
    {
        if (left == 0 && right == 0)
        {
        	//cout << cur << endl;
        	svec.push_back(cur);
        	return;
        }
        
        if (left != 0)
        	generateParenthesisRecursive(left - 1, right, cur + "(", svec);
        
        if (right > left && right != 0)
        	generateParenthesisRecursive(left, right - 1, cur + ")", svec);
    }
    
    
    vector<string> generateParenthesis(int n) {
        vector<string> svec;
    	generateParenthesisRecursive(n, n, "", svec);
    	return svec;	
    }

Log in to reply
 

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