โ
๐ LeetCode 70๋ฒ
Climbing Stairs - LeetCode
Can you solve this real interview question? Climbing Stairs - You are climbing a staircase. It takes n steps to reach the top. Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? Example 1: Input: n = 2 Outpu
leetcode.com

์ฌ๋ผ๊ฐ์ผ ํ๋ ๊ณ๋จ์ ์: n
n์ผ๋ก ์ฌ๋ผ๊ฐ๊ธฐ ์ํ ๊ฒฝ์ฐ์ ์๋ n-1์์ 1์นธ or n-2์์ 2์นธ ์ฌ๋ผ ๊ฐ๋ ๋ ๊ฐ์ง ๋ฐฉ๋ฒ์ด ์๋ค.
-> ํผ๋ณด๋์น ์์ ๊ฐ๋ค!
๐ฉ๐ปโ๐ป ๋ด ํ์ด
class Solution:
def climbStairs(self, n: int) -> int:
if n == 1:
return 1
fibo = [1,2]
for i in range(2,n):
fibo.append(fibo[i-1]+fibo[i-2])
return fibo[-1]
๐ LeetCode 746๋ฒ
Min Cost Climbing Stairs - LeetCode
Can you solve this real interview question? Min Cost Climbing Stairs - You are given an integer array cost where cost[i] is the cost of ith step on a staircase. Once you pay the cost, you can either climb one or two steps. You can either start from the ste
leetcode.com

์ฌ๋ผ๊ฐ๋๋ฐ ์ธ๋ฑ์ค ๋ง๋ค ๊ฐ๊ฐ arr = [ 1, 2, 4, 6, 2, 4, 6, 1 ]์ ๋น์ฉ์ด ๋๋ ๊ณ๋จ์ด ์๋ค.
๊ณ๋จ์ 1์นธ or 2์นธ ์ฌ๋ผ๊ฐ ์ ์๋ค.
F(0)์ผ๋ก ์ฌ๋ผ๊ฐ๋๋ฐ ๋๋ ๋น์ฉ์ 0
F(1)์ผ๋ก ์ฌ๋ผ๊ฐ๋๋ฐ ๋๋ ๋น์ฉ๋ 0
F(2)์ผ๋ก ์ฌ๋ผ๊ฐ๋ ๊ฒฝ์ฐ์ ์๋ F(0)์์ 2์นธ ์ฌ๋ผ๊ฐ๊ธฐ or F(1)์์ 1์นธ ์ฌ๋ผ๊ฐ๊ธฐ
โ arr[0],arr[1]์ ์ต์๊ฐ : min(F(0)+1,F(1)+2) = 1
F(3)์ผ๋ก ์ฌ๋ผ๊ฐ๋ ๊ฒฝ์ฐ์ ์๋ F(1)์์ 2์นธ ์ฌ๋ผ๊ฐ๊ธฐ or F(2)์์ 1์นธ ์ฌ๋ผ๊ฐ๊ธฐ
โ arr[1], arr[2]์ ์ต์๊ฐ : min(F(1)+arr[1], F(2)+arr[2]) = min(0+2, 1+4) = 2
.
.
์๊ฐ ๋ณต์ก๋ : O(n)
๊ณต๊ฐ ๋ณต์ก๋ : O(n) โ ์ฌ์ค์ ์ ์ฅํ๋๋ฐ ํ์ํ ๊ณต๊ฐ์ 2์นธ์ด๋ฏ๋ก O(1)๋ก ์ค์ผ ์ ์๋ค.
๐ฉ๐ปโ๐ป ๋ด ํ์ด
class Solution:
def minCostClimbingStairs(self, cost: List[int]) -> int:
arr=[0,0]
for i in range(2,len(cost)+1):
# print(f'{i}๋ฒ์งธ {arr[i-2]+cost[i-2]} {arr[i-1]+cost[i-1]}')
arr.append(min(arr[i-2]+cost[i-2], arr[i-1]+cost[i-1]))
return arr[-1]
'Algorithm > ๋์ ๊ณํ๋ฒ' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[Dynamic Programming] ๋์ ๋ฐ๊พธ๊ธฐ - ์ด๊ธ (0) | 2023.10.20 |
---|---|
[Dynamic Programming] ์ต์ ๋น์ฉ ๊ตฌํ๊ธฐ - ์ด๊ธ (0) | 2023.10.20 |
[Dynamic Programming] ๋ค์ด๋๋ฏน ํ๋ก๊ทธ๋๋ฐ์ ๊ธฐ์ด (0) | 2023.10.20 |