01-24 00:19
Recent Posts
Recent Comments
๊ด€๋ฆฌ ๋ฉ”๋‰ด

miinsun

[Algorithm]์•Œ๊ณ ๋ฆฌ์ฆ˜ ์ž๋ฐ”_58 ๋™์ „ ๊ตํ™˜ ๋ณธ๋ฌธ

Algorithm/Java

[Algorithm]์•Œ๊ณ ๋ฆฌ์ฆ˜ ์ž๋ฐ”_58 ๋™์ „ ๊ตํ™˜

miinsun 2022. 3. 2. 19:19

 

๐Ÿ’ฌ ๋ฌธ์ œ ์„ค๋ช…

๋‹ค์Œ๊ณผ ๊ฐ™์ด ์—ฌ๋Ÿฌ ๋‹จ์œ„์˜ ๋™์ „๋“ค์ด ์ฃผ์–ด์ ธ ์žˆ์„๋•Œ ๊ฑฐ์Šค๋ฆ„๋ˆ์„ ๊ฐ€์žฅ ์ ์€ ์ˆ˜์˜ ๋™์ „์œผ๋กœ ๊ตํ™˜ํ•ด์ฃผ๋ ค๋ฉด ์–ด๋–ป๊ฒŒ ์ฃผ๋ฉด ๋˜๋Š”๊ฐ€?

๊ฐ ๋‹จ์œ„์˜ ๋™์ „์€ ๋ฌดํ•œ์ • ์“ธ ์ˆ˜ ์žˆ๋‹ค.

 

 

๐Ÿ”จ ์ž…์ถœ๋ ฅ ์˜ˆ

 

์ž…๋ ฅ - ์ฒซ ๋ฒˆ์งธ ์ค„์—๋Š” ๋™์ „์˜ ์ข…๋ฅ˜๊ฐœ์ˆ˜ N(1<=N<=12)์ด ์ฃผ์–ด์ง„๋‹ค.

๋‘ ๋ฒˆ์งธ ์ค„์—๋Š” N๊ฐœ์˜ ๋™์ „์˜ ์ข…๋ฅ˜๊ฐ€ ์ฃผ์–ด์ง€๊ณ ,

๊ทธ ๋‹ค์Œ์ค„์— ๊ฑฐ์Šฌ๋Ÿฌ ์ค„ ๊ธˆ์•ก M(1<=M<=500)์ด ์ฃผ์–ด์ง„๋‹ค.๊ฐ ๋™์ „์˜ ์ข…๋ฅ˜๋Š” 100์›์„ ๋„˜์ง€ ์•Š๋Š”๋‹ค.

3
1 2 5
15

์ถœ๋ ฅ - ์ฒซ ๋ฒˆ์งธ ์ค„์— ๊ฑฐ์Šฌ๋Ÿฌ ์ค„ ๋™์ „์˜ ์ตœ์†Œ๊ฐœ์ˆ˜๋ฅผ ์ถœ๋ ฅํ•œ๋‹ค. (5 5 5 ๋™์ „ 3๊ฐœ๋กœ ๊ฑฐ์Šฌ๋Ÿฌ ์ค„ ์ˆ˜ ์žˆ๋‹ค.)

3

 

 

โœจ ์•„์ด๋””์–ด

โ€‹

DFS(Level, sum)์œผ๋กœ ์žฌ๊ท€๋ฅผ ์ง„ํ–‰, coins์˜ ํฌ๊ธฐ์— ๋”ฐ๋ผ DFS ๊ฐ€์ง€์˜ ์ˆ˜๋ฅผ ์ง€์ •ํ•œ๋‹ค.

  • ์žฌ๊ท€ ํƒˆ์ถœ ์กฐ๊ฑด
    • sum์ด ๊ฑฐ์Šฌ๋Ÿฌ ์ค„ ๊ธˆ์•ก์„ ๋„˜์œผ๋ฉด return
    • Level๊ฐ’์ด answer๋ณด๋‹ค ํฌ๊ฑฐ๋‚˜ ๊ฐ™์œผ๋ฉด ๋” ์ด์ƒ ๋ณผํ•„์š”๊ฐ€ ์—†๋‹ค.
      • ์ด๋ฏธ ์ตœ์†Œ ๊ฐ’์ด ๊ตฌํ•ด์กŒ๊ธฐ ๋•Œ๋ฌธ
    • ์ตœ์ ์˜ ๋‹ต์„ ๋จผ์ € ๋‚ด๊ธฐ ์œ„ํ•ด์„œ ๋‚ด๋ฆผ์ฐจ ์ˆœ coins๋ฅผ ์ •๋ฆฌํ•˜์ž.

 

 

๐Ÿ’ป Solution.java

import java.util.*;

public class Main {
	static Integer[] coins;
	static int n, m;
	static int min = Integer.MAX_VALUE;
	
	public void DFS(int L, int sum) {
		if(sum > m) return;
		if(L >= min) return;
		if(sum == m) {
			min = Math.min(min, L);
		}
		else {
			for(int i = 0; i < n; i++) {
				DFS(L + 1, sum + coins[i]);
			}
		}
 	}
	
	public static void main(String[] args){
		Main main = new Main();
		Scanner sc = new Scanner(System.in);
		n = sc.nextInt(); // ๋™์ „์˜ ์ข…๋ฅ˜
		coins = new Integer[n];
		for(int i = 0; i < n; i++) 
			coins[i] = sc.nextInt();
		Arrays.sort(coins, Collections.reverseOrder());
		m = sc.nextInt(); // ๊ฑฐ์Šฌ๋Ÿฌ ์ค„ ๊ธˆ์•ก
		
		main.DFS(0, 0);
		System.out.println(min);
		sc.close();
		return ;
	}
}

 

Comments