• 카테고리

    질문 & 답변
  • 세부 분야

    알고리즘 · 자료구조

  • 해결 여부

    미해결

어디가 다른 부분인지 모르겠습니다.

23.01.08 00:32 작성 조회수 222

0

import java.util.Arrays;
import java.util.Scanner;

public class Main {

    static int n;
    static int f;
    static int[] b;
    static int[] p;
    static int[] ch;

    static boolean find = false;

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        n = scanner.nextInt();
        f = scanner.nextInt();

        b = new int[n];
        p = new int[n];
        ch = new int[n + 1];

        for (int i = 0; i < n; i++) {
            b[i] = memoizationFactorial(n - 1, i);
        }
        solution(0, 0);
    }

    public static void solution(int level, int sum) {
        if (find) {
            return;
        }
        if (level == n) {
            if (sum == f) {
                for (int i : p) {
                    System.out.print(i + " ");
                }
            }
            find = true;
        } else {
            for (int i = 1; i <= n; i++) {
                if (ch[i] == 0) {
                    ch[i] = 1;
                    p[level] = i;
                    solution(level + 1, sum + (p[level] * b[level]));
                    ch[i] = 0;
                }
            }
        }
    }

    static int[][] memorize = new int[35][35];

    private static int memoizationFactorial(int n, int c) {
        if (memorize[n][c] > 0) {
            return memorize[n][c];
        }
        if (n == c || c == 0) {
            return 1;
        } else {
            return memorize[n][c] = memoizationFactorial(n - 1, c) + memoizationFactorial(n - 1, c - 1);
        }
    }
}

제가 푼 방식으로는 안풀려서 선생님 코드를 그대로 썼는데 어디가 누락됬는지 모르겠습니다. ㅠㅠ

답변 1

답변을 작성해보세요.

1

안녕하세요^^

if (level == n) {
    if (sum == f) {
        for (int i : p) {
            System.out.print(i + " ");
        }
        find = true;
    }            
}

find = true 위치가 위에 코드처럼 되어야 합니다.