문제 설명
접근법
- 정해진 공식이 보이지 않고 N의 크기가 크지 않아 전체 경우의 수를 파악하는 방식으로 접근했습니다.
정답
import java.util.*;
import java.io.*;
public class Main {
static List<String> result;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
for (int t = 0; t < T; t++) {
result = new LinkedList<String>();
int N = sc.nextInt();
subset(N, 2, "1");
Collections.sort(result);
for (int i = 0; i < result.size(); i++) {
System.out.println(result.get(i));
}
System.out.println();
}
}
public static void subset(int N, int depth, String str) {
if (depth == N + 1) {
if (calculate(str) == 0) {
result.add(str);
}
return;
}
subset(N, depth + 1, str + "+" + Integer.toString(depth));
subset(N, depth + 1, str + "-" + Integer.toString(depth));
subset(N, depth + 1, str + " " + Integer.toString(depth));
}
public static int calculate(String s) {
StringBuilder sb = new StringBuilder();
Deque<String> lst = new LinkedList<String>();
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '+' || s.charAt(i) == '-') {
lst.add(sb.toString());
lst.add(Character.toString(s.charAt(i)));
sb = new StringBuilder();
} else if (s.charAt(i) == ' ') {
continue;
} else {
sb.append(s.charAt(i));
}
}
lst.add(sb.toString());
while (lst.size() != 1) {
int left = Integer.parseInt(lst.pollFirst());
String oper = lst.pollFirst();
int right = Integer.parseInt(lst.pollFirst());
if (oper.equals("+")) {
lst.addFirst(Integer.toString(left + right));
} else if (oper.equals("-")) {
lst.addFirst(Integer.toString(left - right));
} else {
lst.addFirst(Integer.toString(left * 10 + right));
}
}
return Integer.parseInt(lst.getFirst());
}
}