๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Algorithm

[SW Expert Academy] - (D3)2817. ๋ถ€๋ถ„ ์ˆ˜์—ด์˜ ํ•ฉ

by ์ฃผ๋ฐœ2 2020. 7. 19.
๋ฐ˜์‘ํ˜•

https://swexpertacademy.com/main/code/problem/problemDetail.do?contestProbId=AV7IzvG6EksDFAXB&categoryId=AV7IzvG6EksDFAXB&categoryType=CODE

 

SW Expert Academy

SW ํ”„๋กœ๊ทธ๋ž˜๋ฐ ์—ญ๋Ÿ‰ ๊ฐ•ํ™”์— ๋„์›€์ด ๋˜๋Š” ๋‹ค์–‘ํ•œ ํ•™์Šต ์ปจํ…์ธ ๋ฅผ ํ™•์ธํ•˜์„ธ์š”!

swexpertacademy.com

์ฝ”๋“œ

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

public class Solution {
	/*
	 * N:     ์ž์—ฐ์ˆ˜ ๊ฐฏ์ˆ˜
	 * K:     ์ž์—ฐ์ˆ˜๋ฅผ ์„ ํƒํ•ด์„œ ํ•ฉ์ด K๊ฐ€ ๋˜๋Š” ๊ฒฝ์šฐ
	 * arr[]: N๊ฐœ์˜ ์ž์—ฐ์ˆ˜๋ฅผ ๋‹ด์„ ๋ฐฐ์—ด
	 * ans:   ๊ฒฝ์šฐ์˜ ์ˆ˜
	 */
	private static int N;
	private static int K;
	private static int arr[];
	private static int ans;
	
	private static void dfs(int count, int sum) {
		/* ๊ธฐ์ €์‚ฌ๋ก€: ์ž์—ฐ์ˆ˜ x๊ฐœ ์„ ํƒํ•ด์„œ ํ•ฉ์ด K๊ฐ€ ๋˜๋Š” ๊ฒฝ์šฐ */
		if(sum == K) {
			ans ++;
			return;
		}
		
		/* ๊ธฐ์ €์‚ฌ๋ก€: ์ž์—ฐ์ˆ˜ x๊ฐœ์˜ ํ•ฉ์ด K๋ณด๋‹ค ํฐ๊ฒฝ์šฐ || ์„ ํƒํ•œ ์ž์—ฐ์ˆ˜์˜ ๊ฐฏ์ˆ˜๊ฐ€ N๊ฐœ์™€ ๋™์ผํ•œ ๊ฒฝ์šฐ*/
		if(sum > K || count == N) {
			return;
		}
		
		// ์ž๊ธฐ ์ž์‹  ํฌํ•จ
		dfs(count+1, sum+arr[count]);
		
		// ์ž๊ธฐ ์ž์‹  ๋ฏธํฌํ•จ
		dfs(count+1, sum);
	}

	public static void main(String[] args) throws NumberFormatException, IOException {
		BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st;
		StringBuilder sb = new StringBuilder();
		
		int t = Integer.parseInt(bf.readLine());
		
		for(int tc=1; tc<=t; tc++) {
			st = new StringTokenizer(bf.readLine());
			N = Integer.parseInt(st.nextToken());
			K = Integer.parseInt(st.nextToken());
			arr = new int[N];
			ans = 0;
			
			st = new StringTokenizer(bf.readLine());
			for(int i=0; i<N; i++) {
				arr[i] = Integer.parseInt(st.nextToken());
			}
			
			dfs(0, 0);
			System.out.println("#" + tc + " " + ans);
		}
		
		bf.close();
	}

}

ํ’€์ด

nCr ์กฐํ•ฉ ๋ฌธ์ œ.

์žฌ๊ท€ํ•จ์ˆ˜๋ฅผ ํ†ตํ•ด ํ•ด๊ฒฐํ•˜๊ณ , ์žฌ๊ท€ํ•จ์ˆ˜์˜ ์ข…๋ฃŒ ์กฐ๊ฑด์€ ๋‹ค์Œ๊ณผ ๊ฐ™๋‹ค.

 - ๊ณ ๋ฅธ ์ž์—ฐ์ˆ˜์˜ ํ•ฉ์ด K์™€ ๋™์ผํ•œ ๊ฒฝ์šฐ

 - ๊ณ ๋ฅธ ์ž์—ฐ์ˆ˜์˜ ํ•ฉ์ด K๋ณด๋‹ค ํฌ๊ฑฐ๋‚˜, ๊ณ ๋ฅธ ์ž์—ฐ์ˆ˜์˜ ๊ฐฏ์ˆ˜๊ฐ€ N๊ฐœ์ผ ๊ฒฝ์šฐ

 

dfs ์žฌ๊ท€ ํ˜ธ์ถœ์„ ํ†ตํ•ด ํ˜„์žฌ ์„ ํƒ๋œ ์ˆซ์ž๋ฅผ ํฌํ•จํ•˜๋Š” ๊ฒฝ์šฐ

 - dfs(count+1, sum+arr[count])

 

ํ˜„์žฌ ์„ ํƒ๋œ ์ˆซ์ž๋ฅผ ํฌํ•จํ•˜์ง€ ์•Š๊ณ  ๋‹ค์Œ์œผ๋กœ ๊ฐ€๋Š” ๊ฒฝ์šฐ

 - dfs(count+1, sum)

 

๋กœ ๋‚˜๋ˆ„์–ด ํƒ์ƒ‰์„ ์ง„ํ–‰ํ•จ.

 

๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€

๐Ÿ”HALO