22. Generate Parentheses
Last updated
Last updated
class Solution {
public List<String> generateParenthesis(int n) {
List<String> result = new ArrayList<>();
gen(0, 0, "", result, n);
return result;
}
private void gen(int left, int right, String s, List<String> result, int n) {
//termiator
if (left == n && right == n) {
result.add(s);
}
// drill down
if (left < n) {
gen(left + 1, right, s + "(", result, n);
}
if (left > right) {
gen(left, right + 1, s + ")", result, n);
}
}
}class Solution {
public List<String> generateParenthesis(int n) {
List<String> result = new ArrayList<>();
gen(n, n, "", result);
return result;
}
private void gen(int left, int right, String s, List<String> result) {
//termiator
if (left == 0 && right == 0) {
result.add(s);
return;
}
// drill down
if (left > 0) {
gen(left - 1, right, s + "(", result);
}
if (right > left) {
gen(left, right - 1, s + ")", result);
}
}
}