알고리즘/백준
[문제] 백준 1182번 부분수열의 합
양순이
2021. 3. 9. 06:09
728x90
1182번: 부분수열의 합
첫째 줄에 정수의 개수를 나타내는 N과 정수 S가 주어진다. (1 ≤ N ≤ 20, |S| ≤ 1,000,000) 둘째 줄에 N개의 정수가 빈 칸을 사이에 두고 주어진다. 주어지는 정수의 절댓값은 100,000을 넘지 않는다.
www.acmicpc.net
내 풀이
부분집합 구하는 공식으로 풀면 빠르게 풀리는 문제!
단, 합이 0일 때 공집합 제외해주는 것 잊지 말자
public class BOJ_1182 {
static int N, S;
static int[] arr;
static int answer = 0;
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(in.readLine()," ");
N = Integer.parseInt(st.nextToken());
S = Integer.parseInt(st.nextToken());
arr = new int[N];
st=new StringTokenizer(in.readLine()," ");
for(int i=0;i<N;i++) {
arr[i] = Integer.parseInt(st.nextToken());
}
subset(0,new boolean[N]);
System.out.println(answer);
}
// 부분집합 다 구해보기
static void subset(int cnt, boolean[] checked) {
if(cnt==N) {
int sum=0; // 부분집합의 총합
int count = 0;
for(int i=0;i<N;i++) {
if(checked[i]) {
sum += arr[i];
count++;
}
}
// 공집합 제외
if(sum==S && count>0) answer++;
return;
}
checked[cnt] = true;
subset(cnt+1, checked);
checked[cnt] = false;
subset(cnt+1, checked);
}
}
728x90