알고리즘/백준
[문제] 백준 1182번 부분수열의 합
양순이
2021. 2. 15. 07:54
728x90
1182번: 부분수열의 합
첫째 줄에 정수의 개수를 나타내는 N과 정수 S가 주어진다. (1 ≤ N ≤ 20, |S| ≤ 1,000,000) 둘째 줄에 N개의 정수가 빈 칸을 사이에 두고 주어진다. 주어지는 정수의 절댓값은 100,000을 넘지 않는다.
www.acmicpc.net
풀이
부분집합을 다 구하면 된다.
주의할 점은 S = 0인 경우 공집합도 가능하니까 이때는 total을 하나 빼야 한다.
public class BOJ_1182 {
static int N, S;
static int[] numbers;
static int total = 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());
numbers = new int[N];
st = new StringTokenizer(in.readLine()," ");
for(int i=0;i<N;i++) {
numbers[i] = Integer.parseInt(st.nextToken());
}
subset(0, new boolean[N]);
if(S == 0)
System.out.println(total-1);
else
System.out.println(total);
}
static void subset(int cnt, boolean[] visited) {
if(cnt == N) {
int sum = 0;
for(int i =0;i<N;i++) {
if(visited[i]) {
sum += numbers[i];
}
}
if(sum == S) total++;
return;
}
visited[cnt] = true;
subset(cnt+1, visited);
visited[cnt] = false;
subset(cnt+1, visited);
}
}
728x90