【牛客网】最小邮票数

链接: https://www.nowcoder.com/questionTerminal/83800ae3292b4256b7349ded5f178dd1
来源:牛客网

[编程题]最小邮票数
    有若干张邮票,要求从中选取最少的邮票张数凑成一个给定的总值。    如,有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);
            }
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值