"022-generate parentheses (Generate parentheses)"
"leetcode-Interview algorithm classic-java Implementation" "All topics Directory Index"
Original Question
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:
"((()))""(()())""(())()""()(())""()()()"
Main Topic
Given n pairs of parentheses, output all of their correct combinations
Thinking of solving problems
Using recursive solution to test
Code Implementation
Algorithm implementation class
ImportJava.util.ArrayList;ImportJava.util.LinkedList;ImportJava.util.List;/** * Author: Wang Junshu * date:2015-06-22 * time:11:13 * declaration:all rights Reserved!!! */ Public class solution { PublicList<string>generateparenthesis(intN) {//Queue to save resultslist<string> result =NewArraylist<> ();//number of brackets greater than 0 if(N >0) {//捛 using Arrays Char[] parentheses =New Char[2* N];//Problem SolvingSolve (n, n, parentheses, result); }returnResult }/** * @param left remaining number of open brackets available * @param Right The remaining number of closing parentheses available * @param Pare Ntheses to the last time the parentheses were used * @param result set of result storage * / Public void Solve(intLeftintRightChar[] parentheses, list<string> result) {the number of parentheses remaining cannot be less than 0, and the number of closing parentheses left at each time cannot be less than the number of opening parentheses if(Left <0|| Right <0|| Right < left) {//Do not do anything}///left and right brackets are used . Else if(left = =0&& right = =0) {Result.add (NewString (parentheses)); }//Can be used Else{//location currently in use intIDX = parentheses.length-left-right;//Use left parenthesisPARENTHESES[IDX] =' (';//Recursive solutionSolve (left-1, right, parentheses, result);//Use closing parenthesisPARENTHESES[IDX] =' ) '; Solve (left, right-1, parentheses, result); } }}
Evaluation Results
Click on the picture, the mouse does not release, drag a position, release after the new window to view the full picture.
Special Instructions
Welcome reprint, Reprint please indicate the source "http://blog.csdn.net/derrantcm/article/details/47016125"
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
leetcode-Interview Algorithm classic-java implementation "" 022-generate parentheses (generate parentheses) "