回溯。
这题做得比较愉快,半个小时就通过了。
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Solution {
public List<String> generateParenthesis(int n) {
List<String> result = new ArrayList<String>();
if (n <= 0) {
return result;
}
int leftCount = 0;
int availableLeftCount = 0;
char[] solution = new char[n * 2];
Arrays.fill(solution, '-');
int i = 0;
while (i >= 0) {
if (solution[i] == '-') {
//try left
if (leftCount < n) {
solution[i] = '(';
leftCount++;
availableLeftCount++;
i++;
} else {
solution[i] = ')';//put a right
availableLeftCount--;
i++;
}
} else if (solution[i] == '(') {
//remove the '('
leftCount--;
availableLeftCount--;
if (availableLeftCount > 0) { //put a ')'
solution[i] = ')';
availableLeftCount--;
i++;
} else { //back
solution[i] = '-';
i--;
}
} else if (solution[i] == ')') {
//remove the ')'
availableLeftCount++;
solution[i] = '-';
i--;
}
if (i == n * 2) { //get a solution
String s = new String(solution);
//System.out.println(s);
result.add(s);
i--;
}
}
return result;
}
public static void main(String[] args) {
Solution s = new Solution();
s.generateParenthesis(4);
}
}