Skip to content

Commit 4a6e0cc

Browse files
authored
feat: add python code
1 parent 272f3cb commit 4a6e0cc

File tree

1 file changed

+47
-1
lines changed

1 file changed

+47
-1
lines changed

problems/322.coin-change.md

Lines changed: 47 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,8 @@ eg: 对于 [1,2,5] 组成 11 块
7373

7474
## 代码
7575

76-
* 语言支持:JS,C++
76+
77+
* 语言支持:JS,C++,Python3
7778

7879
JavaScript Code:
7980
```js
@@ -116,6 +117,51 @@ public:
116117
}
117118
};
118119
```
120+
121+
Python3 Code:
122+
123+
124+
(二维数组)
125+
126+
```python
127+
class Solution:
128+
def coinChange(self, coins: List[int], amount: int) -> int:
129+
if amount < 0:
130+
return - 1
131+
dp = [[amount + 1 for _ in range(len(coins) + 1)]
132+
for _ in range(amount + 1)]
133+
# 初始化第一行为0,其他为最大值(也就是amount + 1)
134+
135+
for j in range(len(coins) + 1):
136+
dp[0][j] = 0
137+
138+
for i in range(1, amount + 1):
139+
for j in range(1, len(coins) + 1):
140+
if i - coins[j - 1] >= 0:
141+
dp[i][j] = min(
142+
dp[i][j - 1], dp[i - coins[j - 1]][j] + 1)
143+
else:
144+
dp[i][j] = dp[i][j - 1]
145+
146+
return -1 if dp[-1][-1] == amount + 1 else dp[-1][-1]
147+
```
148+
149+
150+
(一维数组)
151+
152+
```python
153+
class Solution:
154+
def coinChange(self, coins: List[int], amount: int) -> int:
155+
dp = [amount + 1] * (amount + 1)
156+
dp[0] = 0
157+
158+
for i in range(1, amount + 1):
159+
for j in range(len(coins)):
160+
if i >= coins[j]:
161+
dp[i] = min(dp[i], dp[i - coins[j]] + 1)
162+
163+
return -1 if dp[-1] == amount + 1 else dp[-1]
164+
```
119165
## 扩展
120166

121167
这是一道很简单描述的题目, 因此很多时候会被用到大公司的电面中。

0 commit comments

Comments
 (0)