https://leetcode.com/problems/generate-parentheses
n쌍의 괄호 말 되게 모두 조합해보기
public List<String> generateParenthesis(int n) {
List<String> result = new ArrayList<>();
StringBuilder path = new StringBuilder();
dfs(n, 0, 0, path, result);
return result;
}
private void dfs(int n, int open, int close, StringBuilder path, List<String> result) {
if (open == n && close == n) {
result.add(path.toString());
return;
}
// 1. 여는 괄호 선택
if (open < n) {
path.append('(');
dfs(n, open + 1, close, path, result);
path.deleteCharAt(path.length() - 1);
}
// 2. 닫는 괄호 선택
if (close < open) {
path.append(')');
dfs(n, open, close + 1, path, result);
path.deleteCharAt(path.length() - 1);
}
}