-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path322_Coin_Change.cpp
More file actions
75 lines (70 loc) · 1.79 KB
/
322_Coin_Change.cpp
File metadata and controls
75 lines (70 loc) · 1.79 KB
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#include"struct_define.h"
#include<iostream>
#include<vector>
#include<string>
#include<map>
using namespace std;
static const auto x=[](){
std::ios::sync_with_stdio(false);
std:cin.tie(nullptr);
return nullptr;
}();
class Solution
{
public:
int coinChange(vector<int>& coins, int amount)
{
int n = coins.size();
int dp[n+1][amount+1];
for(int i = 0; i <=n; i++)
dp[i][0] = 0;
for(int i = 0; i <= amount; i++)
dp[0][i] = -1;
dp[0][0]=0;
for(int i = 1; i <= n; i++)
for(int j = 1; j <= amount; j++)
{
int temp = INT32_MAX;
for(int k = 0; k <= j/coins[i-1];k++)
{
int temp2 = dp [i-1][j - k*coins[i-1] ];
if(temp2 >= 0 && temp2+k < temp)
{
temp=temp2+k;
}
}
if(temp == INT32_MAX) dp[i][j]=-1;
else dp[i][j] = temp;
}
printMatrix<int>((int*)dp, n+1, amount+1);
return dp[n][amount];
}
int coinChange2(vector<int>& coins, int amount)
{
int n = coins.size();
int dp[n+1][amount+1];
for(int i = 0; i <=n; i++)
dp[i][0] = 0;
for(int i = 0; i <= amount; i++)
dp[0][i] = INT32_MAX;
dp[0][0]=0;
for(int i = 1; i <= n; i++)
for(int j = 1; j <= amount; j++)
{
int a = dp[i-1][j];
if( j - coins[i-1] >= 0 && dp[i][j-coins[i-1]] < INT32_MAX)
{
dp[i][j] = std::min(a,dp[i][j-coins[i-1]]+1);
}else dp[i][j] = a;
}
printMatrix<int>((int*)dp, n+1, amount+1);
return dp[n][amount] == INT32_MAX ? -1 : dp[n][amount];
}
};
int main(int argc, char const *argv[])
{
Solution sol;
vector<int> coins = {1,2,5};
cout<<sol.coinChange2(coins,11);
return 0;
}