给出不同面值的硬币以及总金额. 试写一函数来计算构成该总额的组合数量. 你可以假设每一种硬币你都有无限个.
样例
样例1
输入: amount = 10 和 coins = [10]
输出: 1
样例2
输入: amount = 8 和 coins = [2, 3, 8]
输出: 3
解释:
有3种方法:
8 = 8
8 = 3 + 3 + 2
8 = 2 + 2 + 2 + 2
注意事项
你可以做出以下假设:
0 <= amount <= 5000
1 <= coin <= 5000
硬币种类不超过 500
结果保证符合 32 位符号整数
思路:对于每一种面值的硬币我们都可以选无限个,但是每种面值的硬币的数量个数都会有个一上限,你当前选的数量*当前面值必须小于等于当前余额,否则就不能选,选完当前面值的硬币我们就跳到下一种面值开始选,这样可以避免一些重复的组合,实现算法我们可以用记忆化搜索来完成。
public class Solution {
/**
* @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
*/
public int change(int amount, int[] coins) {
// write your code here
//初始化dp数组
dp = new int[amount+1][coins.length];
for (int i = 0; i <=amount; i++) {
Arrays.fill(dp[i], -1);
}
return dfs(amount,coins,0);
}
int dp[][];
public int dfs(int m,int []arr,int cur)
{
//当cur等于arr.length代表已经到了结尾,什么可选,如果当前余额刚好为0,返回1。
if(cur==arr.length&&m==0) {
return 1;
}
//没有面值可选,返回0;
if(cur==arr.length) return 0;
//查询,某种状态是否在之前计算过。
if(dp[m][cur]!=-1) return dp[m][cur];
//刚好凑成一种组合,返回1;
if(m==0) {
return 1;
};
int count = 0;
//可选的面值
for (int i = cur; i < arr.length; i++) {
//每种面值可选的数量
for (int j = 1;j*arr[i] <=m; j++) {
count += dfs(m-j*arr[i],arr,i+1);
}
}
//记入每种状态的结果
return dp[m][cur] = count;
}
}