题解 | #兑换零钱#
兑换零钱
http://www.nowcoder.com/practice/67b93e5d5b85442eb950b89c8b77bc72
完全背包模版题
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
int n = reader.nextInt();
int aim = reader.nextInt();
int[] arr = new int[n + 1];
for (int i = 1; i <= n; i++) {
arr[i] = reader.nextInt();
}
int[] dp = new int[aim + 1];
// 完全背包
Arrays.fill(dp, Integer.MAX_VALUE - 10001);
dp[0] = 0;
for (int i = 1; i <= aim; i++) {
for (int j = 1; j <= n; j++) {
if (i >= arr[j]) {
dp[i] = Math.min(dp[i - arr[j]] + 1, dp[i]);
}
}
}
if (dp[aim] == Integer.MAX_VALUE - 10001)
System.out.println(-1);
else
System.out.println(dp[aim]);
}
}