Problem Description
假设一堆由1分、2分、5分组成的n个硬币总面值为m分,求一共有多少种可能的组合方式(某种面值的硬币可以数量可以为0)。
Input
输入数据第一行有一个正整数T,表示有T组测试数据;
接下来的T行,每行有两个数n,m,n和m的含义同上。
接下来的T行,每行有两个数n,m,n和m的含义同上。
Output
对于每组测试数据,请输出可能的组合方式数;
每组输出占一行。
每组输出占一行。
Sample Input
2
3 5
4 8
Sample Output
1
2
看到该题的思路是母函数求解,想了一下DFS也可以,以下的DFS方法AC的代码,
之后有空再补个母函数的代码。
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
while ((T--) != 0) {
int n = sc.nextInt();
int m = sc.nextInt();
System.out.println(dfs(5,n,m));
}
}
public static int dfs(int current, int n, int m) {
int count = 0;
if(n ==0 && m == 0)
return 1;
if(n==0 || m<1)
return 0;
if (current == 5) {
count = count + dfs(5, n - 1, m - 5);
count = count + dfs(2, n - 1, m - 2);
count = count + dfs(1, n - 1, m - 1);
} else if (current == 2) {
count = count + dfs(2, n - 1, m - 2);
count = count + dfs(1, n - 1, m - 1);
} else if (current == 1 ) {
count = count + dfs(1, n - 1, m - 1);
}
return count;
}
}
DP做法
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
while (T-- != 0) {
int n = sc.nextInt();
int m = sc.nextInt();
int[][] dp = new int[n + 1][m + 1];
int[] data = {1, 2, 5};
dp[0][0] = 1;
for (int i = 0; i < 3; i++) {
for (int j = 1; j <= n; j++) {
for (int k = data[i]; k <= m; k++) {
dp[j][k] += dp[j - 1][k-data[i]];
}
}
}
System.out.println(dp[n][m]);
}
}
}