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:
"((()))", "(()())", "(())()", "()(())", "()()()"
Thinking Analysis: This problem is very easy to think of using DFS. Into the search problem solver, the state is the currently formed parenthesis string. The goal is to search out all the valid parenthesis strings. The search tree divides two branches at a time, which is followed by an opening parenthesis or a closing parenthesis. When implemented, however, it is important to maintain two counter,leftremain and rightremain to maintain the number of left and right brackets that are currently remaining with the insertion. Whenleftremain > Rightremain, it means that there are a lot of other left parenthesis remaining, which is not possible to have a legal solution in the subtree, since the closing parenthesis can find the left parenthesis that have been added to the left. The left parenthesis can only be matched with the newly added right parenthesis, which requires a direct return of the branch. when leftremain <=rightremain, continue Dfs. When leftremain and Rightremain are all 0 o'clock, and all 2*n brackets are inserted to complete. Add a legal solution. (Note that there is no need to use a stack to match the inference legitimacy.) Suppose the opening parenthesis equals the number of closing parentheses and begins with an opening parenthesis. Then it must be legal, all right brackets can find the appropriate opening parenthesis)
ac Code
public class Solution {public static list<string> res; Public list<string> generateparenthesis (int n) { res = new arraylist<string> (); if (n <= 0) return res; DFS ("", N, N); return res; } void DFS (String state, int leftremain, int rightremain) { if (Leftremain > Rightremain) { return; } if (Leftremain = = 0 && Rightremain = = 0) { res.add (state); return; } if (Leftremain > 0) { DFS (state + "(", leftRemain-1, Rightremain); } if (Rightremain > 0) { DFS (state + ")", Leftremain, rightRemain-1);}}}
Leetcode Generate Parentheses