N과 M- 백트래킹
import sys
input = sys.stdin.readline
N, M = map(int, input().split())
from itertools import permutations
lst = [i for i in range(1, N+1)]
for per in permutations(lst, M):
for p in per:
print(p, end = " ")
print()
1182. 부분수열의합
- 조합으로 해서 합이 M이 되는 개수 구하는 방법 -> 내 풀이
import sys
input = sys.stdin.readline
N, M = map(int, input().split())
lst = [int(i) for i in input().split()]
print(lst)
from itertools import combinations
count = 0
for i in range(1, N+1):
for comb in combinations(lst, i):
if sum(comb) == M:
count+= 1
print(count)
- 백트래킹, dfs로 선택 o,x 로 하기
재귀함수로 해당 원소를 선택하는지, 안하는지를 구현한다.
import sys
input = sys.stdin.readline
N, M = map(int, input().split())
lst = [int(i) for i in input().split()]
count =0
def dfs(level, total):
global count
if level ==N:
if total == M:
count += 1
return
dfs(level+1, total + lst[level])
dfs(level+1, total)
dfs(0,0)
if M ==0:
count -= 1
print(count)
18429. 근손실: 조건 찾기 / 백트래킹
import sys
input = sys.stdin.readline
N, k = map(int, input().split())
lst = list(map(int, input().split()))
print(lst)
visited = [0] * N
count = 0
def dfs(level, current):
global count
if current < 500:
return
if level == N:
count += 1
return
current -=k
for i in range(N):
if not visited[i]:
visited[i] =1
dfs(level+1, current + lst[i] )
visited[i] = 0
dfs(0,500)
print(count)
11729. 하노이탑 / 재귀
N = int(input())
def hanoi(n, start, mid, end):
if n ==1:
print(start, end)
else:
hanoi(n-1, start, end, mid)
print(start, end)
hanoi(n-1, mid, start, end)
print(2**N -1)
hanoi(N, 1,2,3)
15686. 치킨 집 / 조건, 조합, 2차원
import sys
input = sys.stdin.readline
N, M = map(int, input().split())
lst = [list(map(int, input().split())) for _ in range(N)]
house = []
chicken = []
for i in range(N):
for j in range(N):
if lst[i][j] ==1:
house.append((i, j))
elif lst[i][j] ==2:
chicken.append((i,j))
result = float("inf")
print(house, chicken)
from itertools import combinations
for comb in combinations(chicken, M):
total = 0
for x, y in house:
chi_len = float("inf")
for cx, cy in comb:
chi_len = min(chi_len, abs(x-cx) + abs(y-cy))
total+= chi_len
result = min(result, total)
print(result)