-
Notifications
You must be signed in to change notification settings - Fork 52
/
coinChange.cpp
54 lines (40 loc) · 1.14 KB
/
coinChange.cpp
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
// question link: https://leetcode.com/problems/coin-change/
#include <bits/stdc++.h>
using namespace std;
int ans(vector<int>& coins,vector<vector<int>> &dp,int i,int amount)
{
if(amount==0)
return 0;
if(amount<0 || i<0)
return 1e8;
if(dp[i][amount]!=-1)
return dp[i][amount];
if(amount<coins[i])
return dp[i][amount]=ans(coins,dp,i-1,amount);
return dp[i][amount]=min(1+ans(coins,dp,i,amount-coins[i]),
ans(coins,dp,i-1,amount));
}
int coinChange(vector<int>& coins, int amount)
{
int n=coins.size();
vector<vector<int>> dp(n,vector<int>(amount+1));
for(int i=0;i<n;i++)
{
for(int j=0;j<=amount;j++)
dp[i][j]=-1;
}
int v=ans(coins,dp,n-1,amount);
return (v==1e8)?-1:v;
}
int main()
{
int n;
cin>>n;
vector<int> coins(n);
for(int i=0;i<n;i++)
cin>>coins[i];
int amount;
cin>>amount;
cout<<coinChange(coins,amount);
return 0;
}