分析:
首先这个题是一个完全背包问题,把面额看做是商品总金额看做背包容量,找出所有可能装满背包的方案。
首先想到肯定是动态规划,关键是找出动量关系式
例如:用1,2,5金额
已知0元的情况,直接不用任何面值可以记为1种情况。
1.当我们只有1元硬币的时候,只有一种结果
2.当我们有了2元硬币的时候,结果等于 没有2元硬币的结果数+确定用了一枚2元硬币下其余的金额随意搭配
3.到这里逻辑和转化方程就都已经清楚了f [i][j] = f [i − 1][j] + f [i][j − x]
最后拿总额11来再说明下:
可以是之前没有5元面值的时候凑出11元的方案
也可以是需要有5元面值硬币的时候凑出6元的方案加一个5元硬币.
代码:
import java.util.Scanner;
public class G {
public static void main(String[] args) {
int[] countis = {1, 2, 5, 10, 20, 50, 100, 200, 500, 1000, 2000, 5000, 10000};
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for (int i = 0; i < n; i++) {
int x = sc.nextInt();
int dp = dp1(countis, x);
System.out.println(dp);
}
}
/*
*
* @param countis 钱面额集合
* @param number 钱总数
* @return int
*/
public static int dp(int[] countis, int number) {
int[][] answer = new int[countis.length + 1][number + 1];
answer[0][0] = 1;//0个钱 0个面额的时候算一种情况
int k = 0;//k是求得需要用到几个不同的面额数
for (int i : countis) {
if (number >= i) {
k++;
}
}
for (int i = 1; i < k + 1; i++) {
for (int j = 0; j < number + 1; j++) {
//这个位置的值=不用上个面额的值+必须用这个面额的值
answer[i][j] = answer[i - 1][j] + (j - countis[i - 1] >= 0 ? answer[i][j - countis[i - 1]] : 0);
}
}
return answer[k][number];
}
}
优化:
每多出来一种面值硬币的可选项之后,都是在之前已得到方案的结果上进行叠加处理,那么可以只声明一个长度为amount+1的数组,在每多加一种面值硬币的时候就对结果进行重新叠加统计处理。而小于新加的硬币的面值的总额不必处理,和前面说到的情况一样。
1.预定义了dp[0] = 1
2.从面值为1的硬币开始遍历处理,当面值0的情况加1枚1元硬币,可以得到总额1,后面挨个加可以得到[1,1,1,1,1,1,1,1,1,1,1,1]的结果
3.新加入了面值2,在原来的基础上,面值为0的情况加1枚硬币2可以得到总额为2的情况1种,累加上原来面值为2的情况1种,此时可以有2中情况可以凑出面值2,后面依次遍历处理
4.最后新加了面值5,依旧从面值0开始加一个5元面值硬币则代表一种新的凑出5元的方案,加上原来的方案数量3种,此时可知有4种方法凑出5元
5.最后的11元等于之前的6种情况加上使用5元凑出6元的6种方案,一共11种方案
代码:
import java.util.Scanner;
public class G {
public static void main(String[] args) {
int[] countis = {1, 2, 5, 10, 20, 50, 100, 200, 500, 1000, 2000, 5000, 10000};//面额集合
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for (int i = 0; i < n; i++) {
int x = sc.nextInt();
int dp = dp1(countis, x);
System.out.println(dp);
}
}
public static int dp1(int[] countis, int number) {
int k = 0;//k是求得需要用到几个不同的面额数
for (int i : countis) {
if (number >= i) {
k++;
}
}
int[] answer = new int[number + 1];
answer[0] = 1;//0个钱 0个面额的时候算一种情况
for (int i = 0; i < k; i++) {
for (int j = countis[i]; j < number + 1; j++) {
//这个位置的值=不用上个面额的值+必须用这个面额的值
answer[j] += answer[j - countis[i]];
answer[j] %= 1000000007;
}
}
return answer[number];
}
}