Skip to content

Commit

Permalink
2024-11-29打卡
Browse files Browse the repository at this point in the history
  • Loading branch information
NoyeArk committed Nov 29, 2024
1 parent 4c513c0 commit aed49ad
Show file tree
Hide file tree
Showing 3 changed files with 74 additions and 1 deletion.
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
# [265. 粉刷房子 II](https://leetcode.cn/problems/paint-house-ii/description/)

> **作者**:弘树
> **日期**:2024-11-29
> **所用时间**:5min
## 1. 多维动态规划

### 状态表示

1. $f[i][0]$ 表示将第 $i$ 个房子粉刷成红色花费的成本
2. $f[i][1]$ 表示将第 $i$ 个房子粉刷成蓝色花费的成本
3. $f[i][2]$ 表示将第 $i$ 个房子粉刷成绿色花费的成本

### 状态计算

对于当前房子来说,若粉刷成颜色 $i$ ,则要求上一个房子不能为颜色 $i$ ,所以花费的成本为:

$$
f[i] = \min(f[j]) + c, j \in [0, k - 1], j \neq i
$$

最终的答案应为 $\min(f[n][j]), j \in [0, k - 1]$ 。

- 时间复杂度: $O(nk^2)$ ,其中 $n = \text{len}(costs)$
- 空间复杂度: $O(k)$

**Python3**

```python
class Solution:
def minCostII(self, costs: List[List[int]]) -> int:
k = len(costs[0])
f = [0] * k
for cost in costs:
t = f.copy()
for i, c in enumerate(cost):
min_t = min(t[j] for j in range(len(t)) if j != i)
f[i] = min_t + c
return min(f)
```
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@

1. $i$ : 当前判断到数组的第几个元素
2. $last1$ : 数组 $arr1[i - 1]$ 的值
2. $last2$ : 数组 $arr2[i - 1]$ 的值
3. $last2$ : 数组 $arr2[i - 1]$ 的值

如果当 $i == \text{len}(nums)$ 时,说明成功构造出了一个满足题意的 $(arr1, arr2)$ ,返回数量 $1$ 。

Expand Down
32 changes: 32 additions & 0 deletions leetcode/4-每日一题/3251. 单调数组对的数目 II.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
# [3251. 单调数组对的数目 II](https://leetcode.cn/problems/find-the-count-of-monotonic-pairs-ii/description/)

> **作者**:弘树
> **日期**:2024-11-29
## 1. 动态规划 + 前缀和优化

使用记忆化搜索可以通过 I,但是 II 只能通过 797 个测试用例。

之后参考灵神[题解](https://leetcode.cn/problems/find-the-count-of-monotonic-pairs-ii/solutions/2876190/qian-zhui-he-you-hua-dppythonjavacgo-by-3biek)

- 时间复杂度: $O(nm)$
- 空间复杂度: $O(nm)$

**Python3**

```python
class Solution:
def countOfPairs(self, nums: List[int]) -> int:
MOD = 1_000_000_007
n = len(nums)
m = max(nums)
f = [[0] * (m + 1) for _ in range(n)]
for j in range(nums[0] + 1):
f[0][j] = 1
for i in range(1, n):
s = list(accumulate(f[i - 1]))
for j in range(nums[i] + 1):
max_k = j + min(nums[i - 1] - nums[i], 0)
f[i][j] = s[max_k] % MOD if max_k >= 0 else 0
return sum(f[-1][:nums[-1] + 1]) % MOD
```

0 comments on commit aed49ad

Please sign in to comment.