[DP] Hackerank The Coin Change Problem

You can find the problem description here,

Sample Input 1

10 4
2 5 3 6

Sample Output 1

5

This is a typical knapsack problem with repetitions which can be easily solved by making a transaction table from top left to bottom right. The row of the table is the total number of coin to be changed(total weight in knapsack problem), and the column is the denomination of coins. to make the code clean, one row and one column are added. when it comes to cell[r][c] , it depends on the straight upper value and current weight minus current coin denomination as a index on the left:

cell[r][c]=cell[r1][c]+{cell[r][ccoins[r1]]0if(coins[r1]<c)else

The whole table below shows the solving procedure:

Total->:012345678910
Coins:->00000000000
210101010101
510101111112
310111222334
610111232445

code:

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;


long getWays(long n, vector < long > c){
    if (n == 0) return 0;
    vector<vector<long>> ways(c.size() + 1, vector<long>(n + 1, 0)); // ways vector

    for (int s = 1; s < c.size() + 1; ++s) {
        ways[s][0] = 1;
        for (int t = 1; t < n + 1; ++t) {
            ways[s][t] = ways[s-1][t];
            if (c[s-1] <= t) {
                ways[s][t] += ways[s][t-c[s-1]];
            }
        }
    }
    return ways[c.size()][n];
}

int main() {
    int n;
    int m;
    cin >> n >> m;
    vector<long> c(m);
    for(int c_i = 0; c_i < m; c_i++){
       cin >> c[c_i];
    }
    // Print the number of ways of making change for 'n' units using coins having the values given by 'c'
    long ways = getWays(n, c);
    cout << ways << endl;
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值