22. Generate Parentheses
Generate Parentheses
Given n
pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
Example 1:
Input: n = 3 Output: ["((()))","(()())","(())()","()(())","()()()"]
Example 2:
Input: n = 1 Output: ["()"]
Constraints:
1 <= n <= 8
Approach) Dynamic Programming
Once we're all done, we can just return ans.
var generateParenthesis = function(N) {
let ans = [], m = 2 * N
const dfs = (pos, open, seq) => {
if (pos === m) {
let res = new Array(m)
for (let i = 0; i < m; i++)
res[i] = seq & 1 << i ? "(" : ")"
ans.push(res.join(""))
return
}
if (open) dfs(pos+1, open-1, seq)
if (m - pos > open) dfs(pos+1, open+1, seq | 1 << pos)
}
dfs(0, 0, 0)
return ans
};
Approach) Breadth-First Search and Recursion
const generateParentheses = (n) => {
const result = [];
breathFirstSearch("", 0, 0);
return result;
function breathFirstSearch(str, left, right) {
if (left === n && right === n) {
result.push(str);
return;
}
if (left !== n) {
breathFirstSearch(str + "(", left + 1, right);
}
if (left > right) {
breathFirstSearch(str + ")", left, right + 1);
}
}
}
That’s all folks! In this post, we solved LeetCode problem #22. Generate Parentheses
I hope you have enjoyed this post. Feel free to share your thoughts on this.
You can find the complete source code on my GitHub repository. If you like what you learn. feel free to fork 🔪 and star ⭐ it.
In this blog, I have tried to solve leetcode questions & present the most important points to consider when improving Data structure and logic, feel free to add, edit, comment, or ask. For more information please reach me here
Happy coding!
Comments
Post a Comment