백준 - 부분수열의 합(1182)

Brute Force

문제

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

입력

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

출력

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


1) combinations 라이브러리 사용

import sys
from itertools import combinations

n, target = map(int, sys.stdin.readline().split())
li = list(map(int, sys.stdin.readline().split()))
count = 0

for i in range(1, len(li) + 1):
    answer = list(combinations(li, i))
    for idx in range(len(answer)):
        if sum(answer[idx]) == target:
            count += 1
            
print(count)

2) 재귀함수 사용

import sys
input = sys.stdin.readline

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

answer = 0
def subSet(idx, total):
    global answer

    if idx >= n:
        return
    total += li[idx]
    if total == target:
       answer += 1
    subSet(idx + 1, total - li[idx]) # 방금 누적했던 원소값을 다시 빼서 다음 인덱스의 원소값을 더하지 않는 상태
    subSet(idx + 1, total) # 다음 인덱스 원소값을 더한 상태에서 그대로 다시 재귀호출.

subSet(0, 0)
print(answer)

참고)
https://dongsik93.github.io/algorithm/2019/11/13/algorithm-boj-1182/
https://infinitt.tistory.com/274

좋은 웹페이지 즐겨찾기