1. 程式人生 > >leetcode 518. Coin Change 2/硬幣找零 2

leetcode 518. Coin Change 2/硬幣找零 2

sign script 我們 have fun 數量 -c pub NPU

歸納於http://www.cnblogs.com/grandyang/p/7669088.html 原題https://leetcode.com/problems/coin-change-2/description/

518. Coin Change 2(Medium)

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. Note: You can assume that 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 Example 1: Input: amount = 5, coins = [1, 2, 5] Output: 4 Explanation: there are four ways to make up the amount: 5=5 5=2+2+1 5=2+1+1+1 5=1+1+1+1+1

Example 2: Input: amount = 3, coins = [2] Output: 0 Explanation: the amount of 3 cannot be made up just with coins of 2.

Example 3: Input: amount = 10, coins = [10] Output: 1

問題描述

  給一個總錢數amount,給一個硬幣種類數組,每種硬幣的數量你可以想象成足夠大,問:允許使用同種硬幣,一個有多少種硬幣組合方式剛好能湊成總錢數amount? 分析   比如我們有兩個硬幣[1,2],錢數為5,那麽錢數的5的組成方法是可以看作兩部分組成,一種
是由硬幣1單獨組成,那麽僅有一種情況(1+1+1+1+1);另一種是由1和2共同組成,說明我們的組成方法中至少需要由一個2,所以此時我們先取出一個硬幣2,那麽我們只要拼出錢數為3即可,這個3還是可以用硬幣1和2來拼,所以就相當於求由硬幣[1,2]組成的錢數為3的總組合方法數。 動態規劃:dp[i][j]表示用前i個硬幣組成錢數為j的不同組合方法 遞歸式:dp[i][j] = dp[i - 1][j] + (j >= coins[i - 1] ? dp[i][j - coins[i - 1]] : 0);

代碼

class Solution {
public:
    int change(int
amount, vector<int>& coins) { if(amount==0) return 1; if(coins.empty()) return 0; vector<vector<int>> dp(coins.size()+1,vector<int>(amount+1,0)); dp[0][0]=1; //dp[0][j!=0]已被初始化為0了 for(int i=1;i<=coins.size();++i) { dp[i][0]=1; for(int j=1;j<=amount;++j) { if(j>=coins[i-1]) dp[i][j]=dp[i-1][j]+dp[i][j-coins[i-1]]; else dp[i][j]=dp[i-1][j]; /*調試用 printf("dp[%d][%d] = dp[%d-1][%d] + (%d >= coins[%d-1] ? dp[%d][%d - coins[%d-1]] : 0)", i, j, i, j, j, i, i, j, i); printf("= dp[%d][%d] + (%d >= %d ? dp[%d][%d - %d] : 0)", i-1, j,j,coins[i-1],i,j, coins[i - 1]); dp[i][j] = dp[i - 1][j] + (j >= coins[i - 1] ? dp[i][j - coins[i - 1]] : 0); printf("= %d\n\n", dp[i][j]); */ } } return dp[coins.size()][amount]; } };

leetcode 518. Coin Change 2/硬幣找零 2