πŸ“– Problem Solution/Programmers

[Swift] ν”„λ‘œκ·Έλž˜λ¨ΈμŠ€ μœ„ν΄λ¦¬ μ±Œλ¦°μ§€ ν”Όλ‘œλ„

Fomagran πŸ’» 2021. 12. 10. 21:40
728x90
λ°˜μ‘ν˜•

 

Problem

 

 

μ½”λ”©ν…ŒμŠ€νŠΈ μ—°μŠ΅ - ν”Όλ‘œλ„

XXκ²Œμž„μ—λŠ” ν”Όλ‘œλ„ μ‹œμŠ€ν…œ(0 μ΄μƒμ˜ μ •μˆ˜λ‘œ ν‘œν˜„ν•©λ‹ˆλ‹€)이 있으며, 일정 ν”Όλ‘œλ„λ₯Ό μ‚¬μš©ν•΄μ„œ λ˜μ „μ„ νƒν—˜ν•  수 μžˆμŠ΅λ‹ˆλ‹€. μ΄λ•Œ, 각 λ˜μ „λ§ˆλ‹€ νƒν—˜μ„ μ‹œμž‘ν•˜κΈ° μœ„ν•΄ ν•„μš”ν•œ "μ΅œμ†Œ ν•„μš” ν”Όλ‘œλ„"와 던

programmers.co.kr


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

 

728x90
λ°˜μ‘ν˜•