โ† Back to Index

๐Ÿ“š Generate Parentheses โ€“ Java Cheat Sheet

๐Ÿ“Œ What Is It?

The Generate Parentheses problem involves generating all combinations of well-formed parentheses for a given number n.

๐Ÿงฑ Pattern Template

Recursive Backtracking

class Solution {
    public List<String> generateParenthesis(int n) {
        List<String> result = new ArrayList<>();
        backtrack(result, new StringBuilder(), 0, 0, n);
        return result;
    }

    private void backtrack(List<String> result, StringBuilder current, int open, int close, int max) {
        if (current.length() == max * 2) {
            result.add(current.toString());
            return;
        }

        if (open < max) {
            current.append("(");
            backtrack(result, current, open + 1, close, max);
            current.deleteCharAt(current.length() - 1); // Backtrack
        }
        if (close < open) {
            current.append(")");
            backtrack(result, current, open, close + 1, max);
            current.deleteCharAt(current.length() - 1); // Backtrack
        }
    }
}

๐Ÿ“Š Time Complexity

โœ… Use Cases

๐Ÿ“˜ Common LeetCode Problems

๐Ÿงช Example

Input: n = 3
Output: ["((()))", "(()())", "(())()", "()(())", "()()()"]

Explanation:
- For n = 3, generate all valid combinations of 3 pairs of parentheses.

๐Ÿ’ก Pro Tips