[Baekjoon] 1182번 부분수열의 합

Updated:

문제

N개의 정수로 이루어진 수열이 있을 때, 크기가 양수인 부분수열 중에서 그 수열의 원소를 다 더한 값이 S가 되는 경우의 수를 구하는 프로그램을 작성하시오.

입력

첫째 줄에 정수의 개수를 나타내는 N과 정수 S가 주어진다. (1 ≤ N ≤ 20, S ≤ 1,000,000) 둘째 줄에 N개의 정수가 빈 칸을 사이에 두고 주어진다. 주어지는 정수의 절댓값은 100,000을 넘지 않는다.

출력

첫째 줄에 합이 S가 되는 부분수열의 개수를 출력한다.

예제

Example 1:

Input: 
5 0
-7 -3 -2 5 8
Output: 
1

조건

시간 제한 : 2초

메모리 제한 : 256 MB

풀이과정

풀이 1

from itertools import combinations
import sys
n, target = map(int,sys.stdin.readline().split())

li = list(map(int,sys.stdin.readline().split()))
count = 0
for i in range(len(li)):    
    li2 = list(combinations(li,i+1))
    for j in range(len(li2)):
      if sum(li2[j]) == target:
        count+=1
print(count)

itertools의 combinations를 활용해서 모든 경우의 수에 대해 비교해보았다.

풀이 2

n, target = map(int,input().split())

li = list(map(int,input().split()))
length = len(li)

count = 0
for i in range(1 << length):
  sub = []
  for j in range(length):
    if i & (1<<j):
      sub.append(li[j])
  if sum(sub) == target and len(sub) != 0:
    count += 1
print(count)

비트연산을 이용하여 부분집합을 구하여 풀이하였다.

참고 자료

[Python] 비트연산자로 부분집합 구하기

Leave a comment