LeetCode: Generate Parenthesis
Question
- https://leetcode.com/problems/generate-parentheses
- Level: Medium
- Type: DFS
Core Logic
Intuitive[First Attempt]
- So, first, I thought just searching all-possible-parentheses and checking whether those generated parenthesis is valid or not would be great though
- It passed[accepted], but it took 136ms and that is 5% of people who made this.[So top 95%]
- Search All possible one -> Check whether is valid -> Valid? push to answer.
Optimized Logic
- So, after my solution was accepted, I looked up solution[more likely, discussion] for more optimization and was also curious whether how other people made it more faster[like 4ms or less].
- Most of people used DFS Search algorithm like me, but there was a huge difference.
Checking whether generated parenthesis are valid
was the one.- Basically the way I check whether generated parenthesis takes about O(size)
- So roughly, total O(N^2) or more I bet
- But looking at the
pattern
of valid parenthesis that, they always have equal number of single parenthesis. - So, checking with each open-close parenthesis count[whether same or not] would be the first attempt to reduce search space.
- Now, we are 'making' the parenthesis, not 'checking' it.
- Each open/close parenthesis could be added ONLY
n
times- So we are not allowing the case like
((((((((
- So we are not allowing the case like
- If, open count of parenthesis is smaller then close parenthesis, we can close parenthesis to make valid parenthesis
- Each open/close parenthesis could be added ONLY
- So the core logic of this optimized logic would be
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
Author And Source
이 문제에 관하여(LeetCode: Generate Parenthesis), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@kangdroid/LeetCode-Generate-Parenthesis저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)