Skip to content

Commit 2349a9c

Browse files
committed
[1203]ADD:Lc-322
1 parent 464c38a commit 2349a9c

File tree

2 files changed

+59
-0
lines changed

2 files changed

+59
-0
lines changed

Diff for: 动态规划/322. 零钱兑换-Medium.md

+58
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
# [Description](https://leetcode-cn.com/problems/coin-change)
2+
给定不同面额的硬币 coins 和一个总金额 amount。编写一个函数来计算可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。
3+
4+
你可以认为每种硬币的数量是无限的。
5+
6+
 
7+
8+
示例 1:
9+
```python
10+
输入:coins = [1, 2, 5], amount = 11
11+
输出:3
12+
解释:11 = 5 + 5 + 1
13+
```
14+
示例 2:
15+
```python
16+
输入:coins = [2], amount = 3
17+
输出:-1
18+
```
19+
示例 3:
20+
```python
21+
输入:coins = [1], amount = 0
22+
输出:0
23+
```
24+
示例 4:
25+
```python
26+
输入:coins = [1], amount = 1
27+
输出:1
28+
```
29+
示例 5:
30+
```python
31+
输入:coins = [1], amount = 2
32+
输出:2
33+
```
34+
35+
提示:
36+
37+
- $1 <= coins.length <= 12$
38+
- $1 <= coins[i] <= 2^{31} - 1$
39+
- $0 <= amount <= 104$
40+
41+
42+
# Solution
43+
- 时间复杂度:$O(mn)$,m、n分别为len(coins)、amount
44+
- 空间复杂度:$O(n)$
45+
46+
```python
47+
class Solution:
48+
def coinChange(self, coins: List[int], amount: int) -> int:
49+
dp = [amount+1]*(amount+1)
50+
dp[0] = 0
51+
52+
for i in range(1, amount+1):
53+
for coin in coins:
54+
if i - coin >= 0:
55+
dp[i] = min(dp[i], dp[i-coin]+1)
56+
57+
return dp[-1] if dp[-1] != amount+1 else -1
58+
```

Diff for: 动态规划/877. 石子游戏-Medium.md

+1
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@
4141
dp[i][j]=max(piles[i]-dp[i+1][j], piles[j]-dp[i][j-1])
4242
$$
4343
- 最终只需要判断dp[0][len(piles)-1]是否大于0即可(alex是否能比对方多)
44+
- 多说一句:其实本题的dp是在递归的思路上进行优化的,层层剥离的dp就类似于递归的进行过程
4445
```python
4546
class Solution:
4647
def stoneGame(self, piles: List[int]) -> bool:

0 commit comments

Comments
 (0)