๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿ“– Problem Solution/Programmers

[Swift] ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค ์œ„ํด๋ฆฌ ์ฑŒ๋ฆฐ์ง€ ํ”ผ๋กœ๋„

by Fomagran ๐Ÿ’ป 2021. 12. 10.
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
๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€