The question is: 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:
"((()))", "(()())", "(())()", "()(())", "()()()"
I used to solve this problem using string as following codes:
public class Solution {
public List<String> generateParenthesis(int n) {
ArrayList<String> result = new ArrayList<String>();
//StringBuilder s = new StringBuilder();
generate(n, 0, 0, "", result);
return result;
}
public void generate(int n, int left, int right, String s, ArrayList<String> result){
//left is num of '(' and right is num of ')'
if(left < right){
return;
}
if(left == n && right == n){
result.add(s);
return;
}
if(left == n){
//add ')' only.
generate(n, left, right + 1, s + ")", result);
return;
}
generate(n, left + 1, right, s + "(", result);
generate(n, left, right + 1, s + ")", result);
}
}
Now I want to solve this problem using StringBuilder, the code is like this:
import java.util.ArrayList;
public class generateParentheses {
public static ArrayList<String> generateParenthesis(int n) {
ArrayList<String> result = new ArrayList<String>();
StringBuilder sb = new StringBuilder();
generate(n, 0, 0, result, sb);
return result;
}
public static void generate(int n, int left, int right, ArrayList<String> result,
StringBuilder sb) {
if (left < right) {
return;
}
if (left == n && right == n) {
result.add(sb.toString());
sb = new StringBuilder();
return;
}
if (left == n) {
generate(n, left, right + 1, result, sb.append(')'));
return;
}
generate(n, left + 1, right, result, sb.append('('));
//sb.delete(sb.length(), sb.length() + 1);
generate(n, left, right + 1, result, sb.append(')'));
//sb.delete(sb.length(), sb.length() + 1);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(generateParenthesis(4));
}
}
The result is not what I want: (((()))), (((()))))())), (((()))))())))()), (((()))))())))()))(), (((()))))())))()))()))(())), (((()))))())))()))()))(())))()).........
Is there anyone tell me what is the problem? Thank you very much.