输出包括两行,第一行包括两个整数n和aim。第二行包含n个整数,表示arr数组。
输出一个整数,表示换钱的方法数对取模后的答案。
4 15 5 10 25 1
6
5*3=15
10*1+5*1=15
10*1+1*5=15
1*10+5*1=15
5*2+1*5=15
1*15=15
5 1000 2 3 5 7 10
20932712
时间复杂度,空间复杂度。
完全背包求方案数
dp[j]:考虑前 n 种货币,组成面值 j 的方案数
import java.util.Scanner; public class Main { static int N = 20010; static int mod = (int) (1e9 + 7); static int n, aim; static int[] dp = new int[N]; public static void main(String[] args) { Scanner sc = new Scanner(System.in); n = sc.nextInt(); aim = sc.nextInt(); dp[0] = 1; for (int i = 0; i < n; i++) { int v = sc.nextInt(); for (int j = v; j <= aim; j++) { dp[j] = (dp[j] + dp[j - v]) % mod; } } System.out.println(dp[aim]); } }
import java.util.*; public class Main { public static final int mod = 1_000_000_007; public static int process(int[] arr, int n, int aim) { if (arr == null || arr.length == 0) return 0; int[] dp = new int[aim + 1]; for (int i = 0; i < n; i++) { dp[0] = 1; for (int target = 0; target <= aim; target++) { if (target - arr[i] >= 0) { if (i == 0) dp[target] = dp[target - arr[i]]; else dp[target] = (dp[target] + dp[target - arr[i]]) % mod; } } } return dp[aim]; } public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int aim = sc.nextInt(); int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = sc.nextInt(); } System.out.println(process(arr, n, aim)); } }