- 문제 링크: https://www.acmicpc.net/problem/1182
- 시간: 112ms
- 메모리: 14216KB
- DFS
- 공집합 제외: if (S == 0) count--;
package BOJ;
import java.util.*;
import java.io.*;
public class B1182 {
static int N, S, count;
static int[] arr;
public static void dfs(int depth, int sum) {
if (depth == N) {
if (sum == S) count++;
return;
}
dfs(depth+1, sum+arr[depth]);
dfs(depth+1, sum);
}
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
N = Integer.parseInt(st.nextToken());
S = Integer.parseInt(st.nextToken());
st = new StringTokenizer(br.readLine());
arr = new int[N];
for (int i = 0; i < N; i++) {
arr[i] = Integer.parseInt(st.nextToken());
}
dfs(0, 0);
if (S == 0) count--; // 공집합 제외
System.out.println(count);
}
}
반응형
'Java > 코딩테스트' 카테고리의 다른 글
[백준/Silver III] 1 - 4375 (0) | 2025.07.02 |
---|---|
[백준/Bronze II] 시험 감독 - 13458 (0) | 2025.06.30 |
[백준/Bronze I] 디지털 티비 - 2816 (0) | 2025.06.30 |
[백준/Silver III] 카드 놓기 - 18115 (0) | 2025.06.27 |
[java/프로그래머스/12915] 문자열 내 마음대로 정렬하기 (Arrays.sort(strings, (s1, s2) -> s1.charAt(n) - s2.charAt(n)) (0) | 2025.02.27 |