經典回溯算法, 輸入數字,輸出對應括號對
public static void main(String[] args) {
int max=3;
ArrayList<String> result = new ArrayList<String>();
backtrack(result, "", 0, 0 , max);
for (int i = 0; i < result.size(); i++) {
System.out.println(result.get(i));
}
}
public static void backtrack(ArrayList<String> result , String str , int left , int right , int max){
if (str.length() >= max*2 ){
result.add(str);
return;
}
if (left < max ){
backtrack(result, str+"(", left+1, right, max);
}
if (right<left){
backtrack(result, str+")", left, right+1, max);
}
}