72
72
``` python
73
73
class Solution :
74
74
def coinChange (self , coins : List[int ], amount : int ) -> int :
75
- dp = [amount + 1 for i in range (amount + 1 )]
75
+ dp = [amount + 1 ] * (amount + 1 )
76
76
dp[0 ] = 0
77
77
for coin in coins:
78
78
for j in range (coin, amount + 1 ):
@@ -109,16 +109,13 @@ class Solution {
109
109
* @return {number}
110
110
*/
111
111
var coinChange = function (coins , amount ) {
112
- var dp = Array (amount + 1 ).fill (amount + 1 );
112
+ let dp = Array (amount + 1 ).fill (amount + 1 );
113
113
dp[0 ] = 0 ;
114
- for (var i = 1 ; i <= amount; i++ ) {
115
- for (var j = 0 ; j < coins .length ; j++ ) {
116
- if (coins[j] <= i) {
117
- dp[i] = Math .min (dp[i], dp[i - coins[j]] + 1 );
118
- }
114
+ for (const coin of coins) {
115
+ for (let j = coin; j <= amount; ++ j) {
116
+ dp[j] = Math .min (dp[j], dp[j - coin] + 1 );
119
117
}
120
118
}
121
-
122
119
return dp[amount] > amount ? - 1 : dp[amount];
123
120
};
124
121
```
@@ -129,20 +126,14 @@ var coinChange = function (coins, amount) {
129
126
class Solution {
130
127
public:
131
128
int coinChange(vector<int >& coins, int amount) {
132
- std:: vector<int > dp(amount + 1, - 1);
129
+ vector<int > dp(amount + 1, amount + 1);
133
130
dp[ 0] = 0;
134
- for (int i = 1; i <= amount; i++) {
135
- for (int j = 0; j < coins.size(); j++) {
136
- if (coins[ j] <= i && dp[ i - coins[ j]] != -1) {
137
- // 当 当前值未被计算,或者有更小的组成方式的情况下
138
- if (dp[ i] == -1 || dp[ i] > dp[ i - coins[ j]] + 1) {
139
- dp[ i] = dp[ i - coins[ j]] + 1;
140
- }
141
- }
131
+ for (auto coin : coins) {
132
+ for (int j = coin; j <= amount; ++j) {
133
+ dp[ j] = min(dp[ j] , dp[ j - coin] + 1);
142
134
}
143
135
}
144
-
145
- return dp[amount];
136
+ return dp[ amount] > amount ? -1 : dp[ amount] ;
146
137
}
147
138
};
148
139
```
0 commit comments