动态规划应用—硬币组合问题

关于硬币组合问题,华为和创新工场面试题,直接上参考链接:http://www.cnblogs.com/python27/p/3303721.html

/* 
 * Filename :coins.cpp
 * Description: solve coin combinations using dynamic programing
 * Complier: g++
 * Author: python27
 */
#include <iostream>
#include <string>
#include <cmath>
#include <vector>

using namespace std;

/****************************************************************
 * coin Combinations: using dynamic programming
 *
 * Basic idea:
 * dp[i][j] = sum(dp[i-1][j-k*coins[i-1]]) for k = 1,2,..., j/coins[i-1]
 * dp[0][j] = 1 for j = 0, 1, 2, ..., sum
 * 
 * Input:
 * coins[] - array store all values of the coins
 * coinKinds - how many kinds of coins there are
 * sum - the number you want to construct using coins
 *
 * Output:
 * the number of combinations using coins construct sum
 *
 * Usage:
 * c[3] = {1, 2, 5};
 * int result = coinCombinations(c, 3, 10);
 *
 ****************************************************************/
int coinCombinations(int coins[], int coinKinds, int sum)
{
    // 2-D array using vector: is equal to: dp[coinKinds+1][sum+1] = {0};
    vector<vector<int> > dp(coinKinds + 1);
    for (int i = 0; i <= coinKinds; ++i)
    {
        dp[i].resize(sum + 1);
    }
    for (int i = 0; i <= coinKinds; ++i)
    {
        for (int j = 0; j <= sum; ++j)
        {
            dp[i][j] = 0;
        }
    }

    //init: dp[i][0] = 1; i = 0, 1, 2 ..., coinKinds
    //Notice: dp[0][0] must be 1, althongh it make no sense that
    //using 0 kinds of coins construct 0 has one way. but it the foundation
    //of iteration. without it everything based on it goes wrong
    for (int i = 0; i <= coinKinds; ++i)
    {
        dp[i][0] = 1;
    }

    // iteration: dp[i][j] = sum(dp[i-1][j - k*coins[i-1]])
    // k = 0, 1, 2, ... , j / coins[i-1]
    for (int i = 1; i <= coinKinds; ++i)
    {
        for (int j = 1; j <= sum; ++j)
        {
			dp[i][j] = 0;
            for (int k = 0; k <= j / coins[i-1]; ++k)
            {
                dp[i][j] += dp[i-1][j - k * coins[i-1]];
            }
		}
    }

    return dp[coinKinds][sum];
}

int main()
{
    int coins[8] = {1, 2, 5, 10, 20, 50, 100, 200};
    int sum = 200;
	//int coins[2] = {2, 3};
	//int sum = 11;
    int result = coinCombinations(coins, 8, sum);
    cout << "combinations are: " << endl;
    cout << result << endl;

	system("pause");
    return 0;
}



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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值