โ† All problems

22. Generate Parentheses

MediumOpen on LeetCodeProblem statement

Problem Statement

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:

Java โ€” backtrack

Source file
class Solution {
    List<String> ans = new ArrayList<>();

    public List<String> generateParenthesis(int n) {
        solve("", 0, 0, n);
        return ans;
    }

    void solve(String s, int lt, int rt, int n) {
        if (s.length() == 2 * n)
            ans.add(s);
        if (lt < n)
            solve(s + "(", lt + 1, rt, n);
        if (rt < lt)
            solve(s + ")", lt, rt + 1, n);
    }
}