ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค - ํ”ผ๋กœ๋„(Swift)

2022. 10. 18. 14:08ใ†ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค-Swift

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค - ํ”ผ๋กœ๋„(Swift)

 

 

 ๋ฌธ์ œ ์„ค๋ช…

 

https://school.programmers.co.kr/learn/courses/30/lessons/87946

 

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค

์ฝ”๋“œ ์ค‘์‹ฌ์˜ ๊ฐœ๋ฐœ์ž ์ฑ„์šฉ. ์Šคํƒ ๊ธฐ๋ฐ˜์˜ ํฌ์ง€์…˜ ๋งค์นญ. ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค์˜ ๊ฐœ๋ฐœ์ž ๋งž์ถคํ˜• ํ”„๋กœํ•„์„ ๋“ฑ๋กํ•˜๊ณ , ๋‚˜์™€ ๊ธฐ์ˆ  ๊ถํ•ฉ์ด ์ž˜ ๋งž๋Š” ๊ธฐ์—…๋“ค์„ ๋งค์นญ ๋ฐ›์œผ์„ธ์š”.

programmers.co.kr

 

 ๋‚˜์˜ ํ’€์ด

 

๋˜์ „์˜ ๊ฐœ์ˆ˜๊ฐ€ ์ตœ๋Œ€ 8๊ฐœ์ด๊ธฐ ๋•Œ๋ฌธ์— ์ „์ฒด๋ฅผ ํƒ์ƒ‰ํ•ด๋„ ๋œ๋‹ค๊ณ  ์ƒ๊ฐํ–ˆ๋‹ค.

์ด๋ฅผ DFS๋กœ ๊ตฌํ˜„ํ–ˆ๋Š”๋ฐ check๋ฐฐ์—ด์„ ํ†ตํ•ด์„œ ๊ฐ”๋˜ ๊ณณ์€ ํƒ์ƒ‰ํ•˜์ง€ ๋ชปํ•˜๊ฒŒ ์„ค์ •ํ–ˆ๋‹ค. 

 

import Foundation

func solution(_ k:Int, _ dungeons:[[Int]]) -> Int {
    
    func DFS(_ L: Int, _ leftedHP: Int, _ sum: Int) {
        if sum > cnt {
            cnt = sum
        }
        for i in 0..<dungeons.count {
            if ch[i] == false {
                if leftedHP >= dungeons[i][0] {
                    ch[i] = true
                    DFS(L+1, leftedHP-dungeons[i][1], sum+1)
                    ch[i] = false
                }
            }
        }
    }
    
    var cnt = 0
    var ch = [Bool](repeating: false, count: dungeons.count)
    DFS(0, k, 0)
    
    return cnt
}

 

๊ธ€์„ ์ ์œผ๋ฉด์„œ sum๋ณ€์ˆ˜๊ฐ€ ๊ผญ ํ•„์š”ํ•œ์ง€์— ๋Œ€ํ•ด ์ƒ๊ฐํ–ˆ๊ณ  ๊ฒฐ๊ตญ ์ง€์šฐ๊ณ  ์ด ์ฝ”๋“œ์—์„œ๋Š” ๊นŠ์ด๊ฐ€ ๊ณง ๋‹ด์„ ์ˆ˜ ์žˆ๋Š” ๊ฐœ์ˆ˜์ด๊ธฐ ๋•Œ๋ฌธ์— L๊ณผ cnt๋ฅผ ๋น„๊ตํ•ด์„œ ๋‹ต์„ ๋„ฃ์–ด์ฃผ์—ˆ๋‹ค.

 

import Foundation

func solution(_ k:Int, _ dungeons:[[Int]]) -> Int {
    
    func DFS(_ L: Int, _ leftedHP: Int) {
        if L > cnt {
            cnt = L
        }
        for i in 0..<dungeons.count {
            if ch[i] == false {
                if leftedHP >= dungeons[i][0] {
                    ch[i] = true
                    DFS(L+1, leftedHP-dungeons[i][1])
                    ch[i] = false
                }
            }
        }
    }
    
    var cnt = 0
    var ch = [Bool](repeating: false, count: dungeons.count)
    DFS(0, k)
    
    return cnt
}