풀이 아이디어
dfs가 i번 스테이지에 도착한다
↓
지금까지 구매한 번들을 검사한다
↓
현재 스테이지 번호(i + 1)의 힌트 개수를 센다
↓
cost[i]에서 사용할 수 있는 최대 개수로 제한한다
↓
현재 스테이지 해결 비용 cost[i][used_hint]를 계산한다
↓
마지막 스테이지인가?
├─ 맞음: 해결 비용을 더하고 answer 갱신
└─ 아님:
├─ 현재 번들을 사지 않고 다음 스테이지
└─ 현재 번들을 산 새 배열을 만들어 다음 스테이지
답안 코드
function solution(cost, hint) {
var answer = Infinity;
let buy_hint = [];
function dfs(buy_hint, costs, i, sum) {
let used_hint = 0;
if (buy_hint.length > 0) {
for (let a = 0; a < buy_hint.length; a++) {
const hint_idxs = buy_hint[a].slice(1);
for (let c = 0; c < hint_idxs.length; c++) {
if (hint_idxs[c] === i + 1) {
used_hint += 1;
}
}
}
}
used_hint = Math.min(used_hint, cost[i].length - 1);
if (i === cost.length - 1) {
answer = Math.min(answer, sum + cost[i][used_hint]);
return;
}
// 안삼
dfs(buy_hint, costs, i + 1, sum + cost[i][used_hint]);
// 삼
dfs([...buy_hint, hint[i]], costs, i + 1, sum + cost[i][used_hint] + hint[i][0])
}
dfs(buy_hint, cost, 0, 0);
return answer;
}
완성이 되는 답안 코드를 제출하기 전까지의 피드백 과정
cost가 아니라 숫자 하나를 넘김dfs(buy_hint, cost[0][0], 0, 0);
왜잘못?
for (let i = 1; i < costs.length; i++)
내부에서는 cost를 배열로 인식해서 돌리고 있는데 하나만 보내니까
costs.length // undefined
발생
수정
dfs(buy_hint, cost, 0, 0);