CodeWars 일백 스물 네 번째 문제
Updated:
All Balanced Parentheses
public static List <String> balancedParens (int n) {
List<String> parenthesisList = new ArrayList<String>();
makeParenthesis(parenthesisList, new char[2*n], 0, n, 0, 0);
return parenthesisList;
}
static void makeParenthesis(List<String> parenthesisList, char parenthesis[], int pos, int n, int open, int close)
{
if(close == n) {
parenthesisList.add(String.valueOf(parenthesis));
return;
} else {
if(open > close) {
parenthesis[pos] = ')';
makeParenthesis(parenthesisList, parenthesis, pos+1, n, open, close+1);
}
if(open < n) {
parenthesis[pos] = '(';
makeParenthesis(parenthesisList, parenthesis, pos+1, n, open+1, close);
}
}
}
- 재귀함수를 사용해서 풀었다.
- 문제를 풀면서 ()을 어떻게 바꿔 나가야 하나가 관건이었다.
- 하지만 최종적으로 ((()))의 형태로 가운데로 모두 몰리기 때문에 open close 변수를 통해서 ()을 어떻게 바꿀지 체크하고 pos를 통해서 해당 위치의 괄호를 바꾼다.