an straight method and very easy to understand with detailed explain


  • 0
    5
    class Solution {
    public:
    	vector<string> generateParenthesis(int n) {
    	    vector<string> result;
                string cur;
    	    helper(result, cur, n, n);
    	    return result;
    	}
    
    	void helper(vector<string> &result, string cur, int left, int right) 
            {
                /*if left = 0 and right = 0 means get the valid result*/
                if (left == 0 && right == 0) {
    	        result.push_back(cur);
    		return;
    	    }
               /*left must greater than zero and greater than right 
               if left < 0 the case (((( will occur if left < right the case ()) ()) will occur, 
               we doesn't need to add right < 0 here just for easily understanding*/
    	    if (left < 0 || (left > right) || right < 0) {
    		return;
    	    }
    
    	    helper(result, cur + '(', left - 1, right);
                helper(result, cur + ')', left, right - 1);
    
    	}
    };
    

Log in to reply
 

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