链接:
https://www.nowcoder.com/questionTerminal/83800ae3292b4256b7349ded5f178dd1
来源:牛客网
来源:牛客网
[编程题]最小邮票数
- 热度指数:3741时间限制:1秒空间限制:65536K
- 算法知识视频讲解
有若干张邮票,要求从中选取最少的邮票张数凑成一个给定的总值。 如,有1分,3分,3分,3分,4分五张邮票,要求凑成10分,则使用3张邮票:3分、3分、4分即可。
输入描述:
有多组数据,对于每组数据,首先是要求凑成的邮票总值M,M<100。然后是一个数N,N〈20,表示有N张邮票。接下来是N个正整数,分别表示这N张邮票的面值,且以升序排列。
输出描述:
对于每组数据,能够凑成总值M的最少邮票张数。若无解,输出0。
示例1
输入
10 5 1 3 3 3 4
输出
3
dfs解法,性能可能不是最优
import java.util.*;
public class Main {
public static void helper(ArrayList<Integer> candidates, ArrayList<Integer> arr, int target, int[] cnt, int start) {
if (target == 0) {
candidates.add(cnt[0]);
return;
}
for (int i = start; i < arr.size() && target >= arr.get(i); ++i) {
++cnt[0];
helper(candidates, arr, target-arr.get(i), cnt, i+1);
--cnt[0];
}
}
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
while (reader.hasNext()) {
int M = reader.nextInt();
int n = reader.nextInt();
ArrayList<Integer> arr = new ArrayList<>();
for (int i = 0; i < n; ++i) {
arr.add(reader.nextInt());
}
int[] cnt = {0};
ArrayList<Integer> candidates = new ArrayList<>();
helper(candidates, arr, M, cnt, 0);
if (candidates.size() > 0) {
System.out.println(Collections.min(candidates));
} else {
System.out.println(0);
}
}
}
}