백준 22839 java : DP, 배낭문제

magicdrill·2024년 12월 2일

백준 문제풀이

목록 보기
498/673

백준 22839 java : DP, 배낭문제

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

public class bj22839 {
    static Scanner scanner = new Scanner(System.in);
    static int [] coinValue = new int[18];

    public static void main(String[] args) {
        int testCase;

        for(int i = 1; i < coinValue.length; i++){
            coinValue[i] = i * i;
            System.out.print(coinValue[i] + " ");
        }
        System.out.println();

        while(true){
            testCase = scanner.nextInt();
            if(testCase == 0){
                break;
            }
            System.out.println(findAnswer(testCase));
        }

        scanner.close();
    }

    public static int findAnswer(int testCase){
        System.out.println("findAnswer()");
        int [] DP = new int[testCase + 1];
        int i, j;

        Arrays.fill(DP, 0);
        DP[0] = 1;

        for (i = 1; i < coinValue.length; i++) {
            if (coinValue[i] > testCase){
                break; // 제곱수가 testCase보다 크면 종료
            }
            for (j = coinValue[i]; j <= testCase; j++) {
                DP[j] = DP[j] + DP[j - coinValue[i]];
            }

            System.out.print("i = " + i + " / coinValue[" + i + "] = " + coinValue[i] + " : ");
            for(j = 1; j <= testCase; j++){
                System.out.print(DP[j] + " ");
            }
            System.out.println();
        }

        return DP[testCase];
    }
}

0개의 댓글