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:
"((()))", "(()())", "(())()", "()(())", "()()()"
还是类似的括号匹配问题,这次是要生成所有可能的匹配组合,思路如下:
首先用迭代法穷举可能出现的所有情况,然后利用已有的isValid()判断是否匹配,进而决定是否储存到返回vector容器中。
class Solution { public: vector<string> generateParenthesis(int n) { mSize = n * 2; init(); string s; genpa(-1, s); return ret; } bool isValid(string s) { stack<char> stk; int nSize = s.size(); for(int i = 0; i!= nSize; ++i) { if(s[i] == ‘{‘ || s[i] == ‘(‘ || s[i]== ‘[‘) { stk.push(s[i]); } else { if(stk.empty()) { return false; } char cElem = stk.top(); if(cElem - s[i] ==-1 || cElem - s[i] == -2) { stk.pop(); continue; } else { return false; } } } if(!stk.empty()) { return false; } return true; } void genpa(int j, string s) { if(j == mSize -1) { if(isValid(s)) { ret.push_back(s); } return; } for(int i = 0; i!= 2; ++i) { genpa(j+1, s+album[i]); } } void init(void) { album[0] = ‘(‘; album[1] = ‘)‘; } private: int mSize; vector<string> ret; char album[2]; };
思路类似,多举一反三。
时间: 2024-11-09 00:06:09