|
| 1 | +package leetcode_study |
| 2 | + |
| 3 | +import io.kotest.matchers.shouldBe |
| 4 | +import org.junit.jupiter.api.Test |
| 5 | + |
| 6 | +/** |
| 7 | + * Leetcode |
| 8 | + * 70. Climbing Stairs |
| 9 | + * Easy |
| 10 | + * |
| 11 | + * ์ฌ์ฉ๋ ์๊ณ ๋ฆฌ์ฆ: Dynamic Programming |
| 12 | + * n๊ฐ์ ๊ณ๋จ์ ์ค๋ฅด๋ ๋ฐฉ๋ฒ = n-1๊ฐ์ ๊ณ๋จ์ ์ค๋ฅด๋ ๋ฐฉ๋ฒ ์ + n-2๊ฐ์ ๊ณ๋จ์ ์ค๋ฅด๋ ๋ฐฉ๋ฒ |
| 13 | + */ |
| 14 | +class ClimbingStairs { |
| 15 | + /** |
| 16 | + * Runtime: 0 ms(Beats: 100.00 %) |
| 17 | + * Time Complexity: O(n) |
| 18 | + * - ๋ฐฐ์ด ์ํ |
| 19 | + * |
| 20 | + * Memory: 33.94 MB(Beats: 18.06 %) |
| 21 | + * Space Complexity: O(n) |
| 22 | + * - n+1 ํฌ๊ธฐ์ ๋ฐฐ์ด ์ฌ์ฉ |
| 23 | + */ |
| 24 | + fun climbStairs1(n: Int): Int { |
| 25 | + if (n == 1) return 1 |
| 26 | + if (n == 2) return 2 |
| 27 | + |
| 28 | + val arr = IntArray(n + 1) |
| 29 | + arr[1] = 1 |
| 30 | + arr[2] = 2 |
| 31 | + for (i in 3..n) { |
| 32 | + arr[i] = arr[i - 1] + arr[i - 2] |
| 33 | + } |
| 34 | + return arr[n] |
| 35 | + } |
| 36 | + |
| 37 | + /** |
| 38 | + * ๋ฐฐ์ด์ ์ฐ์ง ์๊ณ ๋ณ์๋ฅผ ์ฌ์ฉํ์ฌ ๊ณต๊ฐ ๋ณต์ก๋๋ฅผ ๊ฐ์ ํ ๋ฒ์ ์
๋๋ค. |
| 39 | + * Runtime: 0 ms(Beats: 100.00 %) |
| 40 | + * Time Complexity: O(n) |
| 41 | + * - n๋ฒ ์ํ |
| 42 | + * |
| 43 | + * Memory: 34.06 MB(Beats: 15.90 %) |
| 44 | + * Space Complexity: O(1) |
| 45 | + * - ์ฌ์ฉ๋๋ ์ถ๊ฐ ๊ณต๊ฐ์ด ์
๋ ฅ ํฌ๊ธฐ์ ๋ฌด๊ดํ๊ฒ ์ผ์ ํจ |
| 46 | + */ |
| 47 | + fun climbStairs2(n: Int): Int { |
| 48 | + if (n == 1 || n == 2) return n |
| 49 | + var firstCase = 1 |
| 50 | + var secondCase = 2 |
| 51 | + var totalSteps = 0 |
| 52 | + |
| 53 | + for (steps in 3..n) { |
| 54 | + totalSteps = firstCase + secondCase |
| 55 | + firstCase = secondCase |
| 56 | + secondCase = totalSteps |
| 57 | + } |
| 58 | + return totalSteps |
| 59 | + } |
| 60 | + |
| 61 | + @Test |
| 62 | + fun test() { |
| 63 | + climbStairs1(2) shouldBe 2 |
| 64 | + climbStairs1(3) shouldBe 3 |
| 65 | + climbStairs2(2) shouldBe 2 |
| 66 | + climbStairs2(3) shouldBe 3 |
| 67 | + } |
| 68 | +} |
0 commit comments