-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDP Coin Change
More file actions
29 lines (29 loc) · 838 Bytes
/
Copy pathDP Coin Change
File metadata and controls
29 lines (29 loc) · 838 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
//memoization (top-down)
class Solution {
public:
int func(int ind , int amount ,vector<int>&coins, vector<vector<int>>&dp){
if(amount==0)return 0;
if(ind==0){
if(amount%coins[ind]==0)return amount/coins[ind];
else return 1e9;
}
if(dp[ind][amount]!=-1){
return dp[ind][amount];
}
int not_take = 0+func(ind-1,amount,coins,dp);
int take = INT_MAX;
if(coins[ind]<=amount){
take = 1+func(ind,amount-coins[ind],coins,dp);
}
return dp[ind][amount] = min(take,not_take);
}
int coinChange(vector<int>& coins, int amount) {
int n = coins.size();
vector<vector<int>>dp(n,vector<int>(amount+1,-1));
int ans = func(n-1,amount,coins,dp);
if(ans>=1e9){
return -1;
}
return ans;
}
};