Checking whether generated parenthesis are valid
was the one.pattern
of valid parenthesis that, they always have equal number of single parenthesis. n
times((((((((
Instead of checking generated parenthesis, just make valid parenthesis
class Solution {
public:
vector<string> correctAnswer;
void dfs(string& generatedString, int currentDepth, int& pairCount, int openCount, int endCount) {
if (currentDepth == pairCount*2) {
if (openCount != 0 || openCount != 0) return;
correctAnswer.push_back(generatedString);
return;
}
if (openCount > 0) {
generatedString.push_back('(');
dfs(generatedString, currentDepth+1, pairCount, openCount-1, endCount);
generatedString.pop_back();
}
if (openCount < endCount) {
generatedString.push_back(')');
dfs(generatedString, currentDepth+1, pairCount, openCount, endCount-1);
generatedString.pop_back();
}
}
vector<string> generateParenthesis(int n) {
string tmpValue = "";
dfs(tmpValue, 0, n, n, n);
return correctAnswer;
}
};
136ms to 4ms lol