An accepted recursive C++ approach. 10ms.


  • 0
    Y
    class Solution {
    public:
        vector<string> generateParenthesis(int n) {
        	vector<string> v,v1,v2;string s;
        	if(n==0) {v.push_back("");return v;}
        	if(n==1) {v.push_back("()");return v;}
        	for(int i=0;i<n;i++){
        		v1=generateParenthesis(i);
        		v2=generateParenthesis(n-1-i);
        		for(int p=0;p<v1.size();p++){
        			for(int q=0;q<v2.size();q++){
        				s='('+v1[p]+')'+v2[q];
        				v.push_back(s);
        			}
        		}
        		v1.clear();v2.clear();
        	}
        	return v;
        }
    };

Log in to reply
 

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