[BOJ 2294] ๋™์ „2

 

1. ๋ฌธ์ œ : Link

๋™์ „1๊ณผ ๋น„์Šทํ•˜์ง€๋งŒ ์ตœ์†Ÿ๊ฐ’์„ ๊ตฌํ•˜๋Š” ๋ฌธ์ œ

 

2. ํ’€์ด

dp[0]  = 0

๊ฐ dp ๊ฐ’์€ ํ•ด๋‹น ๊ฐ’์—์„œ - ์ฝ”์ธ ํ•œ ๊ฐ’ + 1 (๊ฐœ์ˆ˜๊ฐ€ ํ•˜๋‚˜ ๋Š˜์–ด๋‚˜๋Š”๊ฒƒ)

๊ธฐ์กด dp ๊ฐ’๊ณผ ๋น„๊ตํ•ด์„œ min๊ฐ’ ๋„ฃ์–ด์ฃผ๊ธฐ

 

10001 (์ตœ๋Œ“๊ฐ’)์ด๋ผ๋ฉด -1 ์ถœ๋ ฅ

 

3. ์ฝ”๋“œ

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

public class Main {
    static int N;
    static int sum;
    static int[] coins;
    static int[] dp;

    public static void main(String[] args) throws IOException {
        Scanner sc = new Scanner(System.in);

        N = sc.nextInt();
        sum = sc.nextInt();

        coins = new int[N];

        for(int i=0; i<N; i++){
            coins[i] = sc.nextInt();
        }

        dp = new int[sum+1];
        Arrays.fill(dp, 10001);
        dp[0] = 0;

        for(int i = 0; i < N; i++) {
            for(int j = coins[i]; j <= sum; j++) {
                dp[j] = Math.min(dp[j],dp[j - coins[i]]+1);
            }
        }

        if(dp[sum] == 10001) System.out.println(-1);
        else System.out.println(dp[sum]);

    }
}
  • ๋„ค์ด๋ฒ„ ๋ธ”๋Ÿฌ๊ทธ ๊ณต์œ ํ•˜๊ธฐ
  • ๋„ค์ด๋ฒ„ ๋ฐด๋“œ์— ๊ณต์œ ํ•˜๊ธฐ
  • ํŽ˜์ด์Šค๋ถ ๊ณต์œ ํ•˜๊ธฐ
  • ์นด์นด์˜ค์Šคํ† ๋ฆฌ ๊ณต์œ ํ•˜๊ธฐ