Bracket generation
Problem Description
The number n represents the logarithm of generating brackets. Please design a function to generate all possible and effective bracket combinations.
example:
Problem-solving ideas
Use the backtracking method to exhaustively, use the One_of_ans[2*n] array to store the result, if One_of_ans[i] is 0, it is the right parenthesis, if One_of_ans[i] is 1, it is the left parenthesis, traverse the subset tree to get a feasible solution, Then convert the One_of_ans[] into a string to get the answer to this question.
Code
class Solution {
public List<String> generateParenthesis(int n) {
List<String> res = new ArrayList<String>();
int One_of_ans[] = new int[2*n];
backtrack(res,One_of_ans,2*n,0);
return res;
}
public void backtrack(List<String> res,int One_of_ans[],int n,int t){
//回溯
// System.out.print("现在在第"+t+"层:");
if(t>=n)
output(res,One_of_ans,n);
else{
for(int i=0;i<=1;i++){
One_of_ans[t] = i;
backtrack(res,One_of_ans,n,t+1);
}
}
}
public void output(List<String> res,int One_of_ans[],int n){
//根据整型数组得到结果
if(legal(One_of_ans,n)){
String OneOfAns = "";
for(int i : One_of_ans){
if(i == 0)
OneOfAns = OneOfAns +"(";
else
OneOfAns = OneOfAns+ ")";
}
res.add(OneOfAns);
}
}
public boolean legal(int One_of_ans[],int n){
//判断是否为合法括号
for(int i : One_of_ans)
System.out.print(i);
System.out.println();
Stack<Integer> s = new Stack<>();
for(int i : One_of_ans){
if(i == 0)
s.push(new Integer(1));
else if(s.isEmpty() || !s.pop().equals((Integer)i))
return false;
}
if(!s.isEmpty())
return false;
return true;
}
}
Small summary
Note on the Java grammar obtained from this question:
- The parameter of Java's Stack class is the object type;
- The comparison of object types uses equals() method instead of ==.