Web/Java

엘리스 알고리즘 코드 챌린지 Day5(07월 12일) - Java

helperwoo 2024. 7. 12. 15:55
반응형

문제

 

 

나의 제출(오답)

import java.io.*;
import java.util.*;

public class Main {
    public static BufferedReader br;
    public static BufferedWriter bw;

    public static int n;
    public static int[] s;
    public static boolean[] visited;
    public static int max;
    public static StringBuffer sb = new StringBuffer();

    public static void main(String[] args) throws IOException {
        br = new BufferedReader(new InputStreamReader(System.in));
        bw = new BufferedWriter(new OutputStreamWriter(System.out));

        n = Integer.parseInt(br.readLine());
        s = new int[(int) Math.pow(2, n)];

        StringTokenizer st = new StringTokenizer(br.readLine());
        for (int i=0; i<s.length; i++) {
            s[i] = Integer.parseInt(st.nextToken());
        }
        Arrays.sort(s);
        max = s[s.length-1];

        visited = new boolean[s.length];
        dfs(1, new ArrayList<>(Arrays.asList(s[1])), s[1]);

        bw.flush();
        bw.close();
    }

    public static void dfs(int idx, ArrayList<Integer> result, int sum) throws IOException {
        if (!sb.isEmpty()) return;

        if (result.size() == n) {
            if (sum == max) {
                result.forEach(i -> sb.append(i).append(" "));
                bw.write(sb.toString());
            }

            return;
        }

        visited[idx] = true;
        for (int i=idx+1; i<s.length; i++) {
            if (!visited[i]) {
                ArrayList<Integer> tmp = new ArrayList<>(result);
                tmp.add(s[i]);
                dfs(i, tmp, sum + s[i]);
            }
        }
        visited[idx] = false;
    }
}
반응형