[Swift] νλ‘κ·Έλλ¨Έμ€ μν΄λ¦¬ μ±λ¦°μ§ νΌλ‘λ
Problem
Solution
ν΄λΉ λ¬Έμ λ λ°±νΈλνΉμΌλ‘ νμ΄μΌ νλ λ¬Έμ μ λλ€.
(νΉμ λ°±νΈλνΉμ λͺ¨λ₯΄μλ λΆλ€μ μ¬κΈ° μμ λ³΄κ³ μμ£ΌμΈμ!)
answerλ₯Ό 0λΆν° ννμ μμν΄μ€λλ€.
func solution(_ k:Int, _ dungeons:[[Int]]) -> Int {
var answer:Int = 0
explore(dungeons: dungeons, answer: &answer, k:k, count: 0)
return answer
}
λμ λ€μ μννλ©° μ΅μ νμ νΌλ‘λ(dungeon[0])μ μλͺ¨ νΌλ‘λ(dungeon[1])λ³΄λ€ νμ¬ νΌλ‘λ(k)κ° ν°μ§ λΉκ΅ν΄μ€λλ€.
λ§μ½ 쑰건μ λΆν©νλ€λ©΄ μλ‘μ΄ νΌλ‘λμΈ μλ‘μ΄ νΌλ‘λ(newK)λ₯Ό λ§λ€μ΄μ£Όκ³ νμ¬ νΌλ‘λ(k)μμ μλͺ¨ νΌλ‘λ(dungeon[1])λ₯Ό λΉΌμ€λλ€.
κ·Έλ¦¬κ³ λμ λ€μμ 쑰건μ λΆν©ν λμ μ μμ νκ³ κ°―μ(count)λ₯Ό νλ λλ €μ€ λ€ μ¬κ·ν΄μ€λλ€.
exploreλ₯Ό μ¬κ·νλ©΄μ κ°μ₯ λ§μ κ°―μλ₯Ό μ μ₯ν answerμ countλ₯Ό λΉκ΅ν΄ λ ν° κ°μΌλ‘ answerλ₯Ό λ³κ²½ν΄μ€λλ€.
func explore(dungeons:[[Int]],answer:inout Int,k:Int,count:Int) {
answer = max(answer,count)
for (i,dungeon) in dungeons.enumerated() {
var newDungeons:[[Int]] = dungeons
if dungeon[0] <= k && dungeon[1] <= k{
let newK = k - dungeon[1]
newDungeons.remove(at: i)
explore(dungeons:newDungeons,answer: &answer,k: newK,count: count + 1)
}
}
}
Source Code