File tree Expand file tree Collapse file tree 1 file changed +64
-0
lines changed Expand file tree Collapse file tree 1 file changed +64
-0
lines changed Original file line number Diff line number Diff line change 1+ /*
2+ * @lc app=leetcode id=322 lang=java
3+ *
4+ * [322] Coin Change
5+ *
6+ * https://leetcode.com/problems/coin-change/description/
7+ *
8+ * algorithms
9+ * Medium (31.53%)
10+ * Likes: 2135
11+ * Dislikes: 85
12+ * Total Accepted: 233.5K
13+ * Total Submissions: 738.6K
14+ * Testcase Example: '[1,2,5]\n11'
15+ *
16+ * You are given coins of different denominations and a total amount of money
17+ * amount. Write a function to compute the fewest number of coins that you need
18+ * to make up that amount. If that amount of money cannot be made up by any
19+ * combination of the coins, return -1.
20+ *
21+ * Example 1:
22+ *
23+ *
24+ * Input: coins = [1, 2, 5], amount = 11
25+ * Output: 3
26+ * Explanation: 11 = 5 + 5 + 1
27+ *
28+ * Example 2:
29+ *
30+ *
31+ * Input: coins = [2], amount = 3
32+ * Output: -1
33+ *
34+ *
35+ * Note:
36+ * You may assume that you have an infinite number of each kind of coin.
37+ *
38+ */
39+ class Solution {
40+ public int coinChange (int [] coins , int amount ) {
41+ if (amount < 1 ) {
42+ return 0 ;
43+ }
44+
45+ int [] dp = new int [amount + 1 ];
46+ int sum = 0 ;
47+
48+ while (++sum <= amount ) {
49+ int min = -1 ;
50+ for (int coin : coins ) {
51+ if (sum >= coin && dp [sum - coin ] != -1 ) {
52+ int temp = dp [sum - coin ] + 1 ;
53+ if (min < 0 || temp < min ) {
54+ min = temp ;
55+ }
56+ }
57+ }
58+ dp [sum ] = min ;
59+ }
60+
61+ return dp [amount ];
62+ }
63+ }
64+
You can’t perform that action at this time.
0 commit comments