标签:style blog color io 使用 ar for div cti
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
For example, given n = 3, a solution set is:
"((()))", "(()())", "(())()", "()(())", "()()()"
思路:使用DFS即可。对于每一步,存在两种选择:1) 加入一个左括号;2) 匹配一个左括号。left表示当前parenthese中还未匹配的左括号数;remain表示还能再加入的左括号数。则,left>0表明可以匹配左括号;remain>0表明可以加入新的左括号。
1 class Solution { 2 public: 3 vector<string> generateParenthesis( int n ) { 4 string parenthese; 5 DFS( parenthese, 0, n ); 6 return parentheses; 7 } 8 private: 9 void DFS( string &parenthese, int left, int remain ) { 10 if( left == 0 && remain == 0 ) { 11 parentheses.push_back( parenthese ); 12 return; 13 } 14 if( remain > 0 ) { 15 parenthese.push_back( ‘(‘ ); 16 DFS( parenthese, left+1, remain-1 ); 17 parenthese.erase( parenthese.end()-1 ); 18 } 19 if( left > 0 ) { 20 parenthese.push_back( ‘)‘ ); 21 DFS( parenthese, left-1, remain ); 22 parenthese.erase( parenthese.end()-1 ); 23 } 24 return; 25 } 26 vector<string> parentheses; 27 };
标签:style blog color io 使用 ar for div cti
原文地址:http://www.cnblogs.com/moderate-fish/p/3959399.html