How does Java generate parentheses
This article introduces the relevant knowledge of "how to generate parentheses in Java". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
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: ["(())", "() ()", "()", "() ()"] public class Solution {public List generateParenthesis (int n) {ArrayList result = new ArrayList (); dfs (result, "", n, n) Return result;} / * left and right represents the remaining number of (and) that need to be added. When left > right, there are more ")" placed than "(". Such cases are wrong and the method stops. * / public void dfs (ArrayList result, String s, int left, int right) {if (left > right) / / since left is reduced by one from left, left cannot be less than right return; if (left==0&&right==0) {result.add (s); return;} if (left > 0) {dfs (result, s + "(", left-1, right) / /} if (right > 0) {dfs (result, s + ")", left, right-1);} "how to generate parentheses in Java" is introduced here, thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!