728x90
문제
N개의 정수로 이루어진 수열이 있을 때, 크기가 양수인 부분수열 중에서 그 수열의 원소를 다 더한 값이 S가 되는 경우의 수를 구하는 프로그램을 작성하시오.
입력
첫째 줄에 정수의 개수를 나타내는 N과 정수 S가 주어진다. (1 ≤ N ≤ 20, |S| ≤ 1,000,000) 둘째 줄에 N개의 정수가 빈 칸을 사이에 두고 주어진다. 주어지는 정수의 절댓값은 100,000을 넘지 않는다.
출력
첫째 줄에 합이 S가 되는 부분수열의 개수를 출력한다.
N개의 수 배열에 대한 부분집합 중에서 합이 S가 되는 경우의 수를 찾으면 된다.
그러나 부분수열의 크기가 양수이기 때문에 공집합은 제외해야 한다.
처음에는 sum을 더하는 식으로 했지만, 공집합을 제외하기 위해 boolean 배열을 통해 sum에 더할 것인지 아닌지를 체크하며 재귀를 진행하였다.
package Silver.s2;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class BOJ_1182_부분수열의합 {
static int[] arr;
static boolean[] check;
static int N, S;
static int cnt;
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());
arr = new int[N];
check = new boolean[N];
StringTokenizer input = new StringTokenizer(br.readLine());
for (int i = 0; i < N; i++)
arr[i] = Integer.parseInt(input.nextToken());
// 입력
findSum(0);
System.out.println(cnt);
}
static void findSum(int idx) {
if (idx == N) {
int sum = 0;
int checkZero = 0;
for (int i = 0; i < arr.length; i++) {
if (check[i])
sum += arr[i];
if (!check[i])
checkZero++;
}
if (checkZero != N && sum == S) {
cnt++;
}
return;
}
check[idx] = true;
findSum(idx + 1); // 포함하기
check[idx] = false;
findSum(idx + 1); // 포함 안하기
// 공집합은 빼야됨..
}
}
좀 더 간단한 버전은 공집합인 경우에는 합이 0이고, S가 0인 경우에만 제외하면 되기 때문에 이 경우만 제외하면 된다.
이 경우가 코드도 간단하고 실행시간도 짧았다
package Silver.s2;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class BOJ_1182_부분수열의합 {
static int[] arr;
static int N, S;
static int cnt;
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());
arr = new int[N];
StringTokenizer input = new StringTokenizer(br.readLine());
for (int i = 0; i < N; i++)
arr[i] = Integer.parseInt(input.nextToken());
// 입력
findSum(0, 0);
if (S == 0)
cnt--; // 공집합 제외
System.out.println(cnt);
}
static void findSum(int idx, int sum) {
if (idx == N) {
if (sum == S) {
cnt++;
}
return;
}
findSum(idx + 1, sum + arr[idx]); // 포함하기
findSum(idx + 1, sum); // 포함 안하기
// 공집합은 빼야됨..
}
}
728x90
'문제 풀이 > BOJ' 카테고리의 다른 글
[백준] 4256 - 트리 (자바/Java) (1) | 2022.08.25 |
---|---|
[백준] 1991 - 트리 순회 (0) | 2022.08.24 |
[백준] 11725 - 트리의 부모 찾기 (자바/Java) (1) | 2022.08.23 |
[백준] 2116 - 주사위 쌓기 (자바/Java) (0) | 2022.08.23 |
[백준] 17276 배열 돌리기 (자바/Java) (0) | 2022.08.22 |