题解 | #括号生成#
括号生成
http://www.nowcoder.com/practice/c9addb265cdf4cdd92c092c655d164ca
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param n int整型
* @return string字符串ArrayList
*/
public ArrayList<String> generateParenthesis (int n) {
// write code here
String str = new String();
ArrayList<String> ans = new ArrayList<>();
callBack(ans,str,n,0);
return ans;
if(left == 0 && right == 0){
ans.add(path);
return;
path = path + "(";
int length = path.length();
callBack(ans,path,left - 1,right + 1);
path = path.substring(0,length-1);
}
if(right > 0){
path = path + ")";
int length = path.length();
callBack(ans,path,left,right - 1);
path = path.substring(0,length-1);
}
}
}
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param n int整型
* @return string字符串ArrayList
*/
public ArrayList<String> generateParenthesis (int n) {
// write code here
String str = new String();
ArrayList<String> ans = new ArrayList<>();
callBack(ans,str,n,0);
return ans;
}
//left 左括号剩余数量,right 右括号剩余数量
public void callBack(ArrayList<String> ans,String path,int left,int right){if(left == 0 && right == 0){
ans.add(path);
return;
}
//每次用一个左括号就增加一个右括号
if(left>0){path = path + "(";
int length = path.length();
callBack(ans,path,left - 1,right + 1);
path = path.substring(0,length-1);
}
if(right > 0){
path = path + ")";
int length = path.length();
callBack(ans,path,left,right - 1);
path = path.substring(0,length-1);
}
}
}