dungeon
함수에서 방문할 수 있는 모든 던전의 경우의 수를 다 따져 최대값을 구한다.dungeon
)의 로직dungeon
을 호출한다.import java.util.*;
class Solution {
public int dungeon(int k, List<List<Integer>> now, int count){
int result = count;
for(int i=0; i<now.size(); i++){
int m = now.get(i).get(0);
int c = now.get(i).get(1);
if(k >= m){
List<List<Integer>> next = new ArrayList<>();
next.addAll(now.subList(0, i));
next.addAll(now.subList(i+1, now.size()));
result = Math.max(result, dungeon(k-c, next, count+1));
}
}
return result;
}
public List<List<Integer>> convertIntList(int[][] dungeons){
List<List<Integer>> result = new ArrayList<>();
for(int i=0; i<dungeons.length; i++){
List<Integer> temp = new ArrayList<>();
for(int j=0; j<dungeons[i].length; j++){
temp.add(dungeons[i][j]);
}
result.add(temp);
}
return result;
}
public int solution(int k, int[][] dungeons) {
List<List<Integer>> dungeonList = convertIntList(dungeons);
return dungeon(k, dungeonList, 0);
}
}
[참고] dfs 버전
import java.util.*;
class Solution {
private boolean[] visited;
private int result = 0;
public void dfs(int k, int[][] dungeons, int count){
for(int i=0; i<dungeons.length; i++){
if(!visited[i] && k >= dungeons[i][0]){
visited[i] = true;
dfs(k-dungeons[i][1], dungeons, count+1);
visited[i] = false;
}
}
result = Math.max(result, count);
}
public int solution(int k, int[][] dungeons) {
visited = new boolean[dungeons.length];
dfs(k, dungeons, 0);
return result;
}
}
def dungeon(k, now, count):
result = count
for i in range(len(now)):
m, c = now[i]
if k >= m:
next = now[:i] + now[i+1:]
result = max(dungeon(k-c, next, count+1), result)
return result
def solution(k, dungeons):
return dungeon(k, dungeons, 0)