Generate Parentheses
递归。传入的前两个参数分别表示未分配的左括号数和未匹配的左括号数。
1 void fill(int numOfRemain, int numToMatch, string tmp, vector<string> &result){ 2 if(numOfRemain == 0 && numToMatch == 0){ 3 result.push_back(tmp); 4 return; 5 } 6 if(numOfRemain > 0){ 7 tmp += '('; 8 fill(numOfRemain-1, numToMatch+1, tmp, result); 9 tmp.erase(tmp.length()-1); 10 } 11 if(numToMatch > 0){ 12 tmp += ')'; 13 fill(numOfRemain, numToMatch-1, tmp, result); 14 tmp.erase(tmp.length()-1); 15 } 16 } 17 vector<string> generateParenthesis(int n) { 18 // Start typing your C/C++ solution below 19 // DO NOT write int main() function 20 string tmp; 21 vector<string> vec; 22 fill(n,0,tmp,vec); 23 return vec; 24 }