forked from strang3-r/Leetcode75
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Coin_Change_2_DP.cpp
45 lines (32 loc) · 1.32 KB
/
Coin_Change_2_DP.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
//problem-statement
//You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money.
//Return the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1.
//You may assume that you have an infinite number of each kind of coin.
#include <bits/stdc++.h>
using namespace std;
long countWaysToMakeChange(vector<int>& arr, int n, int T){
vector<vector<long>> dp(n,vector<long>(T+1,0));
//Initializing base condition
for(int i=0;i<=T;i++){
if(i%arr[0]==0)
dp[0][i]=1;
// Else condition is automatically fulfilled,
// as dp array is initialized to zero
}
for(int ind=1; ind<n;ind++){
for(int target=0;target<=T;target++){
long notTaken = dp[ind-1][target];
long taken = 0;
if(arr[ind]<=target)
taken = dp[ind][target-arr[ind]];
dp[ind][target] = notTaken + taken;
}
}
return dp[n-1][T];
}
int main() {
vector<int> arr ={1,2,3};
int target=4;
int n =arr.size();
cout<<"The total number of ways is " <<countWaysToMakeChange(arr,n,target);
}