Skip to content

Commit 8a087b6

Browse files
committed
Sync LeetCode submission Runtime - 367 ms (32.30%), Memory - 40.7 MB (29.35%)
1 parent 8b79ad7 commit 8a087b6

File tree

2 files changed

+70
-0
lines changed

2 files changed

+70
-0
lines changed

0518-coin-change-ii/README.md

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
<p>You are given an integer array <code>coins</code> representing coins of different denominations and an integer <code>amount</code> representing a total amount of money.</p>
2+
3+
<p>Return <em>the number of combinations that make up that amount</em>. If that amount of money cannot be made up by any combination of the coins, return <code>0</code>.</p>
4+
5+
<p>You may assume that you have an infinite number of each kind of coin.</p>
6+
7+
<p>The answer is <strong>guaranteed</strong> to fit into a signed <strong>32-bit</strong> integer.</p>
8+
9+
<p>&nbsp;</p>
10+
<p><strong class="example">Example 1:</strong></p>
11+
12+
<pre>
13+
<strong>Input:</strong> amount = 5, coins = [1,2,5]
14+
<strong>Output:</strong> 4
15+
<strong>Explanation:</strong> there are four ways to make up the amount:
16+
5=5
17+
5=2+2+1
18+
5=2+1+1+1
19+
5=1+1+1+1+1
20+
</pre>
21+
22+
<p><strong class="example">Example 2:</strong></p>
23+
24+
<pre>
25+
<strong>Input:</strong> amount = 3, coins = [2]
26+
<strong>Output:</strong> 0
27+
<strong>Explanation:</strong> the amount of 3 cannot be made up just with coins of 2.
28+
</pre>
29+
30+
<p><strong class="example">Example 3:</strong></p>
31+
32+
<pre>
33+
<strong>Input:</strong> amount = 10, coins = [10]
34+
<strong>Output:</strong> 1
35+
</pre>
36+
37+
<p>&nbsp;</p>
38+
<p><strong>Constraints:</strong></p>
39+
40+
<ul>
41+
<li><code>1 &lt;= coins.length &lt;= 300</code></li>
42+
<li><code>1 &lt;= coins[i] &lt;= 5000</code></li>
43+
<li>All the values of <code>coins</code> are <strong>unique</strong>.</li>
44+
<li><code>0 &lt;= amount &lt;= 5000</code></li>
45+
</ul>

0518-coin-change-ii/solution.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
# Approach 1: Top-down Dynamic Programming
2+
3+
# Time: O(n * amount)
4+
# Space: O(n * amount)
5+
6+
class Solution:
7+
def change(self, amount: int, coins: List[int]) -> int:
8+
def number_of_ways(i, amount):
9+
if amount == 0:
10+
return 1
11+
if i == len(coins):
12+
return 0
13+
if memo[i][amount] != -1:
14+
return memo[i][amount]
15+
16+
if coins[i] > amount:
17+
memo[i][amount] = number_of_ways(i + 1, amount)
18+
else:
19+
memo[i][amount] = number_of_ways(i, amount - coins[i]) + number_of_ways(i + 1, amount)
20+
21+
return memo[i][amount]
22+
23+
memo = [[-1] * (amount + 1) for _ in range(len(coins))]
24+
25+
return number_of_ways(0, amount)

0 commit comments

Comments
 (0)