https://www.acmicpc.net/problem/1182
1182번: 부분수열의 합
첫째 줄에 정수의 개수를 나타내는 N과 정수 S가 주어진다. (1 ≤ N ≤ 20, |S| ≤ 1,000,000) 둘째 줄에 N개의 정수가 빈 칸을 사이에 두고 주어진다. 주어지는 정수의 절댓값은 100,000을 넘지 않는다.
www.acmicpc.net
풀이 1:
dfs로 모든 수열을 구한다음, 0이되는경우를 센다
n,s=map(int,input().split())
nums=[* map(int,input().split())]
visit=[False for _ in range(n)]
cnt=0
tmp=[]
def dfs(start=0):
global cnt
if tmp:
if sum(tmp)==s:
cnt+=1
if len(tmp)==n:
return
for i in range(start,len(nums)):
if not visit[i]:
tmp.append(nums[i])
dfs(i+1)
tmp.pop()
visit
dfs()
print(cnt)
풀이2:
각각의 원소를 포함/포함안하는 2가지 방향으로 뻗어나가는 dfs
n,s=map(int,input().split())
nums=[* map(int,input().split())]
cnt=0
def dfs(v=0,depth=0):
global cnt
if depth==n:
return
v+=nums[depth]
if v==s:cnt+=1
dfs(v,depth+1) #포함하는경우
dfs(v-nums[depth],depth+1) #포함안하는경우(다시빼줌)
dfs()
print(cnt)
어렵ㄷ
'boj' 카테고리의 다른 글
| 백준 11724 연결 요소의 개수 (0) | 2022.04.17 |
|---|---|
| 백준 11723 집합 (0) | 2022.04.16 |
| 백준 2529 부등호 (0) | 2022.04.13 |
| 백준 14889 스타트와 링크 (0) | 2022.04.13 |
| 백준 14051 퇴사 (0) | 2022.04.12 |