728x90
반응형
<문제>
https://www.acmicpc.net/problem/1182
1182번: 부분수열의 합
첫째 줄에 정수의 개수를 나타내는 N과 정수 S가 주어진다. (1 ≤ N ≤ 20, |S| ≤ 1,000,000) 둘째 줄에 N개의 정수가 빈 칸을 사이에 두고 주어진다. 주어지는 정수의 절댓값은 100,000을 넘지 않는다.
www.acmicpc.net
<접근>
파이썬 모듈 중 combinations을 이용하여 부분 수열을 모두 구하고, 해당 부분 수열의 합과 S를 비교하여 같은 개수를 출력한다.
<입력>
from itertools import combinations
N, S = map(int, input().split())
numberSet = list(map(int, input().split()))
combinations를 import한다.
수열의 크기인 N과 원하는 합 S를 입력받는다.
수열을 입력받아 numberSet에 저장한다.
<처리 및 출력>
count = 0
for i in range(1, N+1):
comb_list = list(combinations(numberSet, i))
for j in comb_list:
if sum(j) == S:
count += 1
print(count)
개수를 세어줄 count를 선언한다.
부분 수열의 크기는 1부터 N까지이다. 함수 combinations을 통해 해당 수열의 부분 수열을 list형태로 comb_list에 저장한다. 그리고 comb_list의 각 부분 수열을 더하여 S와 같다면 count를 1 증가시킨다.
결과 값 count를 출력한다.
<전체 코드>
from itertools import combinations
N, S = map(int, input().split())
numberSet = list(map(int, input().split()))
count = 0
for i in range(1, N+1):
comb_list = list(combinations(numberSet, i))
for j in comb_list:
if sum(j) == S:
count += 1
print(count)
728x90
반응형
'# Coding > # 백준' 카테고리의 다른 글
[백준 / 1347] 미로 만들기 - Python (0) | 2021.04.01 |
---|---|
[백준 / 1238] 파티 - Python (0) | 2021.03.31 |
[백준 / 1159] 농구 경기 - Python (0) | 2021.03.29 |
[백준 / 1120] 문자열 - Python (0) | 2021.03.25 |
[백준 / 1076] 저항 - Python (0) | 2021.03.25 |