Skip to content

Commit 51055d5

Browse files
committed
2020-03-07
1 parent 4d71f92 commit 51055d5

File tree

1 file changed

+16
-17
lines changed

1 file changed

+16
-17
lines changed

0322.零钱兑换/0322-零钱兑换.py

Lines changed: 16 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -5,22 +5,21 @@ def coinChange(self, coins, amount):
55
:type amount: int
66
:rtype: int
77
"""
8-
if amount == 0:
9-
return 0
10-
dp = list()
11-
max_int = 2 << 31
8+
from collections import deque
129

13-
for i in range(amount + 1):
14-
if i not in coins:
15-
dp.append(max_int)
16-
else:
17-
dp.append(1)
18-
19-
for i in range(amount + 1):
20-
if i not in coins:
21-
for j in coins:
22-
if i - j > 0:
23-
dp[i] = min(dp[i - j] + 1, dp[i])
10+
queue = deque([(0, 0)])
11+
visited = set([0])
12+
while queue:
13+
cur, step = queue.popleft()
14+
if cur == amount:
15+
return step
16+
if cur > amount:
17+
continue
18+
19+
for coin in coins:
20+
value = cur + coin
21+
if value not in visited:
22+
visited.add((value))
23+
queue.append((value, step + 1))
2424

25-
return dp[amount] if dp[amount] != max_int else -1
26-
25+
return -1

0 commit comments

Comments
 (0)