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:
"((()))", "(()())", "(())()", "()(())", "()()()"Solution:
Recursion-based solution.
Start from keeping track of the number of open and close parentheses.
1. Both the number of open and close parentheses will be n.
2. The number of close parentheses will always less or equal than the number of open parentheses.
public class Solution {
public ArrayList<String> generateParenthesis(int n) {
ArrayList<String> results = new ArrayList<String>();
addParenthesis(0, 0, n, "", results);
return results;
}
public void addParenthesis(int openParen, int closeParen, int n, String str, ArrayList<String> results){
if((openParen == n) && (closeParen == n)){
results.add(str);
}
if(openParen < n){
addParenthesis(openParen+1, closeParen, n, str+"(", results);
}
if(closeParen < openParen){
addParenthesis(openParen, closeParen+1, n, str+")", results);
}
}
}
No comments:
Post a Comment