Coin Change II-LintCode

204 篇文章 0 订阅

You are given coins of different denominations and a total amount of money. Write a function to compute the number of combinations that make up that amount. You may assume that you have infinite number of each kind of coin.

注意事项:

You can assume below:

0 <= amount <= 5000
1 <= coin <= 5000
the number of coins is less than 500
the answer is guaranteed to fit into signed 32-bit integer

样例:
Given amount = 10, coins = [10], return 1
Given amount = 8, coins = [2, 3, 8], return 3
there are three ways to make up the amount:
8 = 8
8 = 3 + 3 + 2
8 = 2 + 2 + 2 + 2

思路:
动态规划,dp[i]表示总额为i时的方案数。
转移方程: dp[i]=Σdp[icoins[j]]
表示 总额为i时的方案数 = 总额为i-coins[j]的方案数的加和。
并初始化dp[0] = 1。

#ifndef C740_H
#define C740_H
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
class Solution {
public:
    /**
    * @param amount: a total amount of money amount
    * @param coins: the denomination of each coin
    * @return: the number of combinations that make up the amount
    */
    int change(int amount, vector<int> &coins) {
        // write your code here
        if (amount == 0 || coins.empty())
            return 0;
        sort(coins.begin(), coins.end());
        vector<int> res(amount+1, 0);
        res[0] = 1;
        for (auto c : coins)
        {
            for (int j = 0; j < res.size(); ++j)
            {
                if (j + c <= amount)
                    res[j + c] += res[j];
            }
        }
        return res[amount];
    }
};
#endif
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值