1 Topics:
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:
"((()))", "(()())", "(())()", "()(())", "()()()"
2 Ideas:
This problem thought for a long time, can't think out solution. Find others to solve with recursion. Https://leetcode.com/discuss/14436/concise-recursive-c-solution
Recursion is a thought ah, a function of thinking?
It is not easy to feel completely learned and used.
M represents the left parenthesis, and N represents the right parenthesis.
3 Code:
PublicList<string> Generateparenthesis (intN) {List<String> result =NewArraylist<string>(); Helper (result,"", N, 0); returnresult; } Private voidHelper (list<string> list,string String,intMintN) { if(M==0 && n==0) {List.add (string); return; } if(M > 0) Helper (list,string+ "(", m-1,n+1); if(n > 0) Helper (list,string+ ")", m,n-1); }
Time complexity, I draw recursive tree, found that the maximum time complexity is O (2^n), there are different views can be a message to discuss together.
[Leetcode 22]generate parentheses