Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
https://leetcode.com/problems/generate-parentheses/
Generate Parentheses - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
n쌍의 괄호가 나올 수 있는 경우의 수를 구하는 문제이다.
이런 문제를 접할때 마다 정말. . 이렇게 간단하게 풀어내는 사람들이 신기할 뿐이다. .
List<String> res = new LinkedList();
public List<String> generateParenthesis(int n) {
dfs(new StringBuilder(), 0, n);
return res;
}
private void dfs(StringBuilder sb, int close, int n) {
if(n==0 && close==0) {
res.add(sb.toString());
return;
}
//Add open parenthese
if(n>0) {
sb.append('(');
dfs(sb, close+1, n-1);
sb.setLength(sb.length()-1);
}
//Add close parenthese
if(close>0) {
sb.append(')');
dfs(sb, close-1, n);
sb.setLength(sb.length()-1);
}
}
'Algorithm > LeetCode' 카테고리의 다른 글
LeetCode 617. Merge Two Binary Trees (0) | 2022.07.06 |
---|---|
LeetCode 763. Partition Labels (0) | 2022.07.04 |
LeetCode 160. Intersection of Two Linked Lists (0) | 2022.06.29 |
LeetCode 21. Merge Two Sorted Lists (0) | 2022.06.29 |
LeetCode 234. Palindrome Linked List (0) | 2022.06.28 |