Algorithm/Problem Solving
[Baekjoon 1182번] 부분수열의 합 문제 (with 자바)
shbada
2021. 9. 26. 18:53
728x90
반응형
문제
https://www.acmicpc.net/problem/1182
1182번: 부분수열의 합
첫째 줄에 정수의 개수를 나타내는 N과 정수 S가 주어진다. (1 ≤ N ≤ 20, |S| ≤ 1,000,000) 둘째 줄에 N개의 정수가 빈 칸을 사이에 두고 주어진다. 주어지는 정수의 절댓값은 100,000을 넘지 않는다.
www.acmicpc.net
풀이코드
package seohae.algorithm.level1;
import java.io.IOException;
import java.util.Arrays;
import java.util.Scanner;
/**
* https://www.acmicpc.net/problem/1182
*/
public class Problem_014_1182 {
static int N;
static int S;
static int[] arr;
static boolean[] visited;
static int cnt;
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
String param = sc.nextLine();
N = Integer.parseInt(param.split(" ")[0]);
S = Integer.parseInt(param.split(" ")[1]);
arr = new int[N];
visited = new boolean[N];
/* 집합 S */
String S = sc.nextLine();
for (int i = 0; i < N; i++) {
arr[i] = Integer.parseInt(S.split(" ")[i]);
}
dfs(0); /* dfs 호출 */
System.out.println(cnt);
}
static void dfs(int value) {
int sum = 0;
boolean isPassed = false; /* S가 0일 경우 sum 되지 않을때 count 방지 */
for (int i = 0; i < N; i++) {
if (visited[i]) { /* true 일 경우 */
sum += arr[i];
isPassed = true;
}
}
/* S 와 합이 동일할 경우 cnt++ 실행 */
if (isPassed && sum == S) {
cnt++;
}
/* 재귀함수 */
for (int j = value; j < N; j++) {
visited[j] = true;
dfs(j + 1);
visited[j] = false;
}
}
}
반응형