https://school.programmers.co.kr/learn/courses/30/lessons/87946
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
- 던전 방문 순서의 모든 조합을 구해야하므로 itertools의 permutations 메소드를 이용해서 완전 탐색해준다.
from itertools import permutations
def solution(k, dungeons):
answer = -1
result = []
for n_dungeons in permutations(dungeons):
cnt = 0
power = k
for i in range(0, len(dungeons)):
if n_dungeons[i][0] <= power and n_dungeons[i][1] <= power:
power -= n_dungeons[i][1]
cnt += 1
result.append(cnt)
answer = max(result)
return answer
from itertools import permutations
def solution(k, dungeons):
answer = 0
for n_dungeons in permutations(dungeons):
cnt = 0
power = k
for i in range(0, len(dungeons)):
if n_dungeons[i][0] <= power and n_dungeons[i][1] <= power:
power -= n_dungeons[i][1]
cnt += 1
if cnt > answer:
answer = cnt
return answer
- 백트랙이라고 하는 것 같은데 dfs로 이 문제를 풀 때 dfs를 재귀호출하고 다시 visited 값을 초기화해주는 방법이다
- 결과적으로 permutations 함수를 쓴 것과 같이 모든 조합에 대해서 방문하게 된다
answer = 0
N = 0
visited = []
def dfs(k, cnt, dungeons):
global answer
if cnt > answer:
answer = cnt
for j in range(N):
if k >= dungeons[j][0] and not visited[j]:
visited[j] = 1
dfs(k - dungeons[j][1], cnt + 1, dungeons)
visited[j] = 0
def solution(k, dungeons):
global N, visited
N = len(dungeons)
visited = [0] * N
dfs(k, 0, dungeons)
return answer
'◦ Algorithm > Python' 카테고리의 다른 글
백준 안전영역 2468 BFS (0) | 2023.04.04 |
---|---|
백준 퍼즐 1525 BFS (0) | 2023.04.04 |
백준 촌수계산 2644 DFS (0) | 2023.04.04 |
백준 토마토 7569 BFS (0) | 2023.03.31 |
프로그래머스 k진수에서 소수 개수 구하기 (0) | 2023.03.31 |