g0001_0100.s0022_generate_parentheses.Solution Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of leetcode-in-java21 Show documentation
Show all versions of leetcode-in-java21 Show documentation
Java-based LeetCode algorithm problem solutions, regularly updated
package g0001_0100.s0022_generate_parentheses;
// #Medium #Top_100_Liked_Questions #Top_Interview_Questions #String #Dynamic_Programming
// #Backtracking #Algorithm_II_Day_11_Recursion_Backtracking #Udemy_Backtracking/Recursion
// #Big_O_Time_O(2^n)_Space_O(n) #2023_08_09_Time_0_ms_(100.00%)_Space_41.7_MB_(97.17%)
import java.util.ArrayList;
import java.util.List;
/**
* 22 - Generate Parentheses\.
*
* Medium
*
* 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`
**/
public class Solution {
public List generateParenthesis(int n) {
StringBuilder sb = new StringBuilder();
List ans = new ArrayList<>();
return generate(sb, ans, n, n);
}
private List generate(StringBuilder sb, List str, int open, int close) {
if (open == 0 && close == 0) {
str.add(sb.toString());
return str;
}
if (open > 0) {
sb.append('(');
generate(sb, str, open - 1, close);
sb.deleteCharAt(sb.length() - 1);
}
if (close > 0 && open < close) {
sb.append(')');
generate(sb, str, open, close - 1);
sb.deleteCharAt(sb.length() - 1);
}
return str;
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy