[M] 22. Generate Parentheses

YJ·3일 전

leetcode

목록 보기
95/100

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);
	}
}

메모

profile
Hello

0개의 댓글