My c++solution use dfs, 3ms

  • 0
    class Solution {
    	string onePossible;
    	vector<string> allPossible;
    	void getans_dfs(string onePossible, int inleft, int inright, int len){
    		if(inleft == 0 && inright == 0) allPossible.push_back(onePossible);
    		if(inleft >0 && inleft <=len/2) getans_dfs(onePossible+'(', inleft-1, inright,len);	
    		if(inright >0 && inright <=len/2 && inleft < inright) getans_dfs(onePossible+')', inleft, inright-1, len);
    	vector<string> generateParenthesis(int n){
    		getans_dfs(onePossible, n, n, n*2);
    		return allPossible;

Log in to reply

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