PS/백준

[백준] (1182) 부분수열의 합 [Python]

munsik22 2025. 3. 21. 22:31

🔗 문제 링크

https://www.acmicpc.net/problem/1182

문제

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

입력

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

출력

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

테스트 케이스

예제 입력 예제 출력
5 0
-7 -3 -2 5 8
1

💻 나의 코드

1st Try:

import sys

def su(index, total):
    global cnt
    if total == s:
        cnt += 1

    if index >= n or total > s:
        return

    su(index + 1, total)
    su(index + 1, total + arr[index])

n, s = map(int, sys.stdin.readline().split())
arr = list(map(int, sys.stdin.readline().split()))

cnt = 0
su(0, 0)
print(cnt)

1시간 동안 엄청나게 고민해서 열심히 코드를 작성했지만 틀려버렸다🤯

2nd Try:

from itertools import combinations
import sys
input = sys.stdin.readline

n, s = map(int, input().split())
arr = list(map(int, input().split()))
cnt = 0

for i in range(1, n+1):
    for j in combinations(arr, i):
        if sum(j) == s:
            cnt += 1

print(cnt)

사실 문제 자체는 itertools 라이브러리의 combinations 모듈을 사용하면 쉽게 풀 수 있었지만, 직접 조합을 구현해보려고 노력했다. 결과적으로는 실패였지만...😇

'PS > 백준' 카테고리의 다른 글

[백준] (1012) 유기농 배추 [Python]  (0) 2025.03.22
[백준] (3190) 뱀 [Python]  (0) 2025.03.22
[백준] (2493) 탑 [Python]  (0) 2025.03.21
[백준] (10819) 차이를 최대로 [Python]  (0) 2025.03.19
[백준] (2468) 안전 영역 [Python]  (0) 2025.03.19