[LeetCode] Generate Parentheses
2019. 12. 30. 19:13ㆍ알고리즘
Loading Question... - 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
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
For example, given n = 3, a solution set is:
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]
이런 류의 문제를 많이 풀어봤다면 단번에 백트래킹이라고 생각할 수 있었을 법한 문제였습니다. 여는 괄호와 닫는 괄호의 갯수를 세어가면서 문제를 풀어나가면 됩니다. 저는 이 괄호 갯수가 다 n개가 되었을 때를 끝내는 시점으로 잡았습니다. 닫는 괄호의 경우에는 앞서 나왔던 여는 괄호의 갯수가 중요하기 때문에 left > right 일 때가 닫는 괄호를 추가할 수 있습니다. 여는 괄호의 경우는 추가 조건 없이 갯수가 n개까지는 계속 추가할 수 있습니다. 이를 백트래킹을 이용하여 풀어내면 다음과 같은 코드로 정리할 수 있습니다.
class Solution {
public:
vector<string> generateParenthesis(int n) {
vector<string> answer;
backtrack(1, 0, n, "(", answer);
return answer;
}
void backtrack(int left, int right, int n, string current, vector<string> &answer) {
if (left == n && right == n) {
answer.push_back(current);
}
if (left < n) {
backtrack(left + 1, right, n, current + "(", answer);
}
if (left > right) {
backtrack(left, right + 1, n, current + ")", answer);
}
}
};
'알고리즘' 카테고리의 다른 글
[LeetCode] Product of Array Except Self (0) | 2020.01.04 |
---|---|
[LeetCode] Top K Frequent Elements (0) | 2019.12.31 |
[LeetCode] Permutations (0) | 2019.12.23 |
[LeetCode] Binary Tree Inorder Traversal (0) | 2019.12.21 |
[프로그래머스] 단어 변환 (0) | 2019.10.30 |