Coin change

本文探讨了硬币找零问题中的两种核心算法:一种用于找出构成特定金额所需的最少硬币数量;另一种则用于计算所有可能的找零组合数。通过动态规划方法,解决了实际应用场景中的找零问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

http://www.fgdsb.com/2015/01/03/coin-change-problem/#more

Given a set of currency denominations, find the minimum number of coins needed to represent an amount.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
int minCoins(int a[], int n, int t){
    vector<int> dp(t+1,0);
    int minVal;
    for(int i = 1; i <= t; i++){
        minVal = i;
        for (int j = 0; j < n; j++)
            if(a[j] <= i)
                minVal = min(dp[i-a[j]]+1,minVal);
            else
                break;
        dp[i] = minVal;
    }
    return dp[t];
}

Follow Up:
How many ways can we make the change?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
int count( int S[], int m, int n ) {
    // table[i] will be storing the number of solutions for
    // value i. We need n+1 rows as the table is consturcted
    // in bottom up manner using the base case (n = 0)
    vector<int> table(n+1, 0);
   
    // Base case (If given value is 0)
    table[0] = 1;
   
    // Pick all coins one by one and update the table[] values
    // after the index greater than or equal to the value of the
    // picked coin
    for(int i=0; i<m; i++)
        for(int j=S[i]; j<=n; j++)
            table[j] += table[j-S[i]];
   
    return table[n];
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值