일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | 6 | 7 |
8 | 9 | 10 | 11 | 12 | 13 | 14 |
15 | 16 | 17 | 18 | 19 | 20 | 21 |
22 | 23 | 24 | 25 | 26 | 27 | 28 |
29 | 30 | 31 |
Tags
- kaggle
- 315. Count of Smaller Numbers After Self
- Generator
- Regular Expression
- LeetCode
- Python
- data science
- iterator
- 30. Substring with Concatenation of All Words
- DWG
- Class
- 컴퓨터의 구조
- t1
- 시바견
- shiba
- 파이썬
- 밴픽
- Convert Sorted List to Binary Search Tree
- Python Implementation
- 운영체제
- Python Code
- attribute
- Protocol
- 프로그래머스
- Decorator
- 43. Multiply Strings
- 715. Range Module
- 109. Convert Sorted List to Binary Search Tree
- concurrency
- Substring with Concatenation of All Words
Archives
- Today
- Total
Scribbling
Dynamic Programming: Finding The Recurrence Relation 본문
Computer Science/Algorithms & Data Structures
Dynamic Programming: Finding The Recurrence Relation
focalpoint 2023. 8. 22. 01:56
https://leetcode.com/problems/paint-fence/
let dp[i] be # of all ways painting i-th fence:
then, dp[i] = num_same(i) + num_diff(i) holds.
(where num_same(i) = painting i-th fence with the same color of i-1-th fence, num_diff(i) with a different color from it)
num_diff(i) = dp[i-1] * (k-1)
num_same(i) = num_diff(i-1) = dp[i-2] * (k-1)
class Solution:
def numWays(self, n: int, k: int) -> int:
if n == 1:
return k
dp = [0] * n
dp[0] = k
dp[1] = k ** 2
for i in range(2, n):
dp[i] = (dp[i-2] + dp[i-1])*(k-1)
return dp[-1]
920. Number of Music Playlists
https://leetcode.com/problems/number-of-music-playlists/description/
Let dp[i, j] = # all ways with i playlist with j different songs
1) adding a new song: dp[i-1, j-1] * (n - j + 1)
2) adding an old song w/o the constraint: dp[i-1, j] * j
3) adding an old song with the constraint: dp[i-1, j] * (j - k) only if j > k
class Solution:
def numMusicPlaylists(self, n: int, goal: int, k: int) -> int:
mod = 10 ** 9 + 7
dp = [[0] * (n+1) for _ in range(goal+1)]
dp[0][0] = 1
for i in range(1, goal+1):
for j in range(1, n+1):
dp[i][j] = dp[i-1][j-1] * (n - j + 1)
if j > k:
dp[i][j] += dp[i-1][j] * (j - k)
dp[i][j] %= mod
return dp[-1][-1]
# top-down approach
# @lru_cache()
# def dp(i, j):
# if i == 0:
# return j == 0
# ret = dp(i-1, j-1) * (n-j+1)
# ret += dp(i-1, j) * max(j-k, 0)
# return ret % (10**9+7)
# return dp(goal, n)
'Computer Science > Algorithms & Data Structures' 카테고리의 다른 글
Design HashMap -- Python Implementation (0) | 2023.10.05 |
---|---|
LeetCode: 173. Binary Search Tree Iterator (0) | 2023.09.30 |
Number of pairs that satisfies the range condition (lower <= p[i] - p[j] <= upper) (0) | 2023.05.15 |
LeetCode: 1639. Number of Ways to Form a Target String Given a Dictionary (0) | 2023.04.07 |
LeetCode: 358. Rearrange String k Distance Apart (0) | 2023.03.10 |