LeetCode: Generate Parenthesis
8289 ワード
Question
Core Logic
Intuitive[First Attempt]
Optimized Logic
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
Code
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;
}
};
Submission
The log of attempts..
136ms to 4ms lol
Reference
この問題について(LeetCode: Generate Parenthesis), 我々は、より多くの情報をここで見つけました https://velog.io/@kangdroid/LeetCode-Generate-Parenthesisテキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol