Sharing my easy understanding C++ 0ms code for generating parentheses


  • 0
    S
        result.push_back("(");
    	left.push_back(1);//存储左边括号数目
    
    	for (int i=0;i<2*n-1;i++){//添加括号的次数
    		int size = result.size();//很重要
    		for(int j=0;j<size;j++){
    				
    			if (left[j]==n)	//左括号达到n,以后只增加右括号
    				result[j].append(")");				 						
    			else if (2*left[j]>result[j].length()){//左括号大于右括号数目
    				 result.push_back(result[j]);//末尾添加一个result[j]
    				 result[j].append(")");	//result[j]的末尾拼一个)
    				 result[result.size()-1].append("(");	//为刚才添加的result[j]的末尾拼一个(
    				 left.push_back(left[j]+1);	//左括号个数加1		
    			} else  { //左括号个数等于右括号个数,只能添加左括号
    				    result[j].append("(");						
    				    left[j] = left[j]+1;
    			}
    		}			
    }
    	return result;

Log in to reply
 

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