[Algorithm] Climbing Stairs

๋ฌธ์ œ ์„ค๋ช…

ํŒŒ๋ผ๋ฉ”ํ„ฐ๋กœ ๋“ค์–ด์˜จ n์นธ์˜ ๊ณ„๋‹จ์ด ์žˆ๋‹ค๊ณ  ๊ฐ€์ •ํ•ด๋ณด์ž. ๊ณ„๋‹จ์€ ํ•œ๋ฒˆ์— 1์นธ ๋˜๋Š” 2์นธ๊นŒ์ง€๋งŒ ์˜ค๋ฅผ ์ˆ˜ ์žˆ๋‹ค. ์ด ๋•Œ n๋ฒˆ์งธ ์นธ๊นŒ์ง€ ๋„๋‹ฌํ•˜๋Š” ๋ฐฉ๋ฒ•์€ ์ด ๋ช‡๊ฐ€์ง€์ผ๊นŒ?

ex) 3์นธ์ด๋ผ๋ฉด 1, 1, 1, 2-1, 1-2 ์ด ์„ธ ๊ฐ€์ง€์˜ ๋ฐฉ๋ฒ•์ด ์กด์žฌํ•œ๋‹ค.

ํ‘ผ ๋ฐฉ๋ฒ•

func climbStairs(_ n: Int) -> Int {
        var result = [1, 1]
        
        for num in 1..<n {
            result.append(result[num] + result[num-1])
        }
        
        return result.last ?? 0
    }

์–ดโ€ฆ ์ด๊ฑธ ์ด๋ ‡๊ฒŒ ํ‘ธ๋Š” ๊ฑด ์•„๋‹ˆ์—ˆ์„ ๊ฒƒ ๊ฐ™์€๋ฐโ€ฆ 2, 3, 5, 8, 13์œผ๋กœ ํ”ผ๋ณด๋‚˜์น˜ ์ˆ˜์—ด์ฒ˜๋Ÿผ ๋‹ต์ด ๋‚˜์˜ค๊ธธ๋ž˜ ๋ƒ…๋‹ค ํ”ผ๋ณด๋‚˜์น˜ ํ•ญ์„ ๋ฐ˜ํ™˜ํ•˜๋„๋ก ๋ฆฌํ„ดํ–ˆ๋Š”๋ฐ ์–ด์ด์—†์ด ์ •๋‹ตโ€ฆ. ์›๋ž˜ ์ด๋ ‡๊ฒŒ ํ‘ธ๋Š”๊ฑฐ์˜€์„๊นŒโ€ฆ?

๊ฒฐ๊ณผ

image

๋ ˆํฌ ์ปค๋ฐ‹

Categories:

Updated:

Leave a comment