Question

Formatted question description: https://leetcode.ca/all/22.html

22	Generate Parentheses

Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

For example, given n = 3, a solution set is:

"((()))", "(()())", "(())()", "()(())", "()()()"

@tag-string

Algorithm

This kind of problem of listing all the results should first consider recursive to solve, because the string has only two characters: left and right parentheses, and the final result must be 3 left parentheses and 3 right parentheses, so two are defined here The variables left and right respectively represent the number of left and right parentheses.

If the number of left parentheses is greater than the number of right parentheses in a certain recursion, it means that the number of right parentheses in the generated string is greater than the number of left parentheses. Number, an illegal string like’)(‘ will appear, so this case will be returned directly without further processing.

If both left and right are 0, it means that the generated string has 3 left brackets and 3 Right parenthesis, and the string is legal, it will be stored in the result and returned. If the above two conditions are not met, if left is greater than 0 at this time, then call the recursive function, pay attention to the update of the parameters, if right is greater than 0, call recursion Function, also update the parameters.

Code

Java

import java.util.ArrayList;
import java.util.List;

public class Generate_Parentheses {

    public class Solution {
        public List<String> generateParenthesis(int n) {
            List<String> res = new ArrayList<String>();
            dfs(n, n, "", res);
            return res;
        }

        void dfs(int left, int right, String out, List<String> res) {
            if (left < 0 || right < 0 || left > right) return;
            if (left == 0 && right == 0) {
                res.add(out);
                return;
            }
            dfs(left - 1, right, out + "(", res);
            dfs(left, right - 1, out + ")", res);
        }
    }
}

All Problems

All Solutions