LeetCode 22: Generate Parentheses Solution

Master LeetCode problem 22 (Generate Parentheses), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

22. Generate Parentheses

Problem Explanation

Explanation

To generate all combinations of well-formed parentheses, we can use a backtracking approach. At each step, we have two choices: either add an open parenthesis '(', or add a close parenthesis ')'. We need to ensure that the parentheses are well-formed by keeping track of the number of open and close parentheses used.

We can start with an empty string and add parentheses recursively while keeping track of the number of open and close parentheses we have used. We can backtrack if we reach a state where the number of open parentheses is greater than n or the number of close parentheses is greater than the number of open parentheses.

The time complexity of this approach is O(4^n / sqrt(n)), where n is the number of pairs of parentheses. The space complexity is O(n) to store the current combination of parentheses.

Solution Code

class Solution {
    public List<String> generateParenthesis(int n) {
        List<String> result = new ArrayList<>();
        generateParenthesisHelper(result, "", 0, 0, n);
        return result;
    }
    
    private void generateParenthesisHelper(List<String> result, String current, int open, int close, int max) {
        if (current.length() == max * 2) {
            result.add(current);
            return;
        }
        
        if (open < max) {
            generateParenthesisHelper(result, current + "(", open + 1, close, max);
        }
        if (close < open) {
            generateParenthesisHelper(result, current + ")", open, close + 1, max);
        }
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 22 (Generate Parentheses)?

This page provides optimized solutions for LeetCode problem 22 (Generate Parentheses) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 22 (Generate Parentheses)?

The time complexity for LeetCode 22 (Generate Parentheses) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 22 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 22 in Java, C++, or Python.

Back to LeetCode Solutions