9.6 Implements an algorithm that prints all valid combinations of n pairs of parentheses (that is, the right and left brackets are paired correctly).
Similar to leetcode:generate parentheses
Solution:
Constructs a string from scratch to avoid repeating strings. In this solution, the left parenthesis and the closing parenthesis are added one at a-only the string remains valid. Each recursive call will have an index that points to a character in the string. We need to select the opening parenthesis or the closing parenthesis, so when can we use the opening parenthesis and when can we use the closing parenthesis?
Opening parenthesis: You can insert an opening parenthesis only if the left parenthesis is not exhausted
Closing parenthesis: You can insert a closing parenthesis only if you do not cause a syntax error. When do syntax errors occur? If the closing parenthesis is more than the left parenthesis, a syntax error occurs.
Therefore, we only need to record the number of left and right brackets allowed to insert. If there is also an opening parenthesis available, insert an opening parenthesis and then recursively. If the closing parenthesis is much better than the left parenthesis (that is, there are more open parentheses in use than the closing parenthesis), insert a closing parenthesis and then recursively.
C + + Implementation code:
#include <iostream>#include<vector>#include<string>using namespacestd;voidHelperintLeftintright,vector<string> &res,string&str) { if(left>Right )return; if(left==0&&right==0) {res.push_back (str); return; } if(left>0) {str+='('; Helper ( Left-1, RIGHT,RES,STR); Str.pop_back (); } if(right>0) {str+=')'; Helper (Left,right-1, RES,STR); Str.pop_back (); }}vector<string> Generateparens (intN) { if(n<=0) returnvector<string>(); Vector<string>ret; stringpath; Helper (N,n,ret,path); returnret;}intmain () {vector<string> Res=generateparens (3); for(auto a:res) cout<<a<<Endl;}
careercup-recursive and dynamic programming 9.6