백준-1182 부분수열의 합

Yeom Jae Seon·2021년 2월 8일
0

알고리즘

목록 보기
11/19
post-thumbnail

문제 ❗

정수의 개수와 합이되어야할 수가 주어진다음
정수의 개수에 맞게 정수들이 입력된다.
주어진 정수들의 조합으로 주어진 합이될 경우의 수를 구하는 문제이다.

풀이 😀

combinations를 이용해서 풀었다.
정수들의 조합이 중복은 되면 안되기 때문에 조합을 통해서 풀었고 combinations를 이용해서 풀었다.

주어진 정수를 arr이라는 리스트에 넣고 for j in combinations(arr, i)를 통해서 i가 1개부터 N개까지의 조합의 경우 합이 S일때를 찾아서 풀었다.

combinations가 존재하니 쉽게 풀었다.

import sys
from itertools import combinations

N, S = map(int, sys.stdin.readline().rstrip().split())
arr = list(map(int, sys.stdin.readline().rstrip().split()))

count = 0

for i in range(1, N + 1):
  for j in combinations(arr, i):
    if sum(j) == S:
      count += 1
print(count)

기억할 부분 😁

  • 파이썬 combinations를 통해서 조합의 경우를 구할수 있다.
from itertools import combinations

arr = [1, 2, 3, 4, 5]
for i in combinations(arr, 3):
  print(i)

# (1, 2, 3)
# (1, 2, 4)
# (1, 2, 5)
# (1, 3, 4)
# (1, 3, 5)
# (1, 4, 5)
# (2, 3, 4)
# (2, 3, 5)
# (2, 4, 5)
# (3, 4, 5)
  • list, 튜플의 합은 sum메소드를 통해서 쉽게 구할수 있다.
arr = [1, 2, 3, 4, 5]
print(sum(arr))

# 15

0개의 댓글