HackerRank/Algorithm/Dynamic Programming/The Coin Change Problem

Problem Summary

Given M types of coins in infinite quantities where the value of each type of coin is given in array C, determine the number of ways to make change for N units using these coins.

Solution

This problem is very similiar to the unbounded knapsack problem (UKP).

Let f[i,j] be the number of ways to make change for j units using coins of types 1,2,…,i. Then we have

f[i,j] = f[i-1,j], if j < c[i]
f[i,j] = f[i-1,j] + f[i,j-c[i]], if j ≥ c[i]

Actually, it is not necessary to use 2-dimensional array. We can only use f[j] instead of f[i,j]. If we enumerate i from 1 to M, the formula is

f[j] = f[j] + f[j-c[i]], if j ≥ c[i]

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <cstdio>
#include <iostream>
using namespace std;
int n,m,c[52];
long long f[252];
int main()
{
scanf("%d%d",&n,&m);
for(int i=1;i<=m;i++) scanf("%d",&c[i]);
f[0]=1;
for(int i=1;i<=m;i++)
for(int j=c[i];j<=n;j++)
f[j]+=f[j-c[i]];
printf("%lld\n",f[n]);
return 0;
}