LINTCODE—— Coin Change II

来源:互联网 发布:子程序铣螺纹怎么编程 编辑:程序博客网 时间:2024/05/16 11:22

LINTCODE—— Coin Change II

题目:给你一个amount,再给你一个硬币数组,coins,数组的值表示为硬币的价值,硬币可以无限使用,求从数组中选择一定的组合满足硬币总价值等于amount有多少种情况

思路:动态规划,类似于无限背包问题,假定dp[j]为从数组coins中选取总价值为j的情况,则不难得出有:dp[j] = dp[j] +dp[j-coins[i]],coins[i]为第i个硬币的价值

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        // write your code here        // 无限背包问题变种        // 初始化dp数组        vector<int> dp(amount+1,0);        dp[0] = 1;        for (int i = 0 ; i < coins.size(); i++) {            for (int j = 1 ; j <= amount; j++) {                if(j >= coins[i])                    dp[j] += dp[j-coins[i]];            }        }        return dp[amount];       }};
原创粉丝点击