PTA甲级考试真题练习68——1068 Find More Coins

题目

在这里插入图片描述

思路

用map<int,int>存下每个币值的硬币数,然后从小往大试即可。有点类似背包问题的递归解法

代码

#include <iostream>
#include <stack>
#include <map>
using namespace std;

map<int, int> coins;
stack<int> res;

bool findCoins(int value) {
	for (auto it = coins.begin(); it != coins.end() && (*it).first <= value; it++) {
		if ((*it).second) {
			coins[(*it).first]--;
			if ((*it).first == value) {
				res.push((*it).first);
				return true;
			}
			else if (findCoins(value - (*it).first)) {
				res.push((*it).first);
				return true;
			}
			else {
				coins[(*it).first]++;
			}
		}
	}
	return false;
}

int main(int argc, char const* argv[])
{
	int n, m;

	cin >> n >> m;
	for (int i = 0; i < n; i++) {
		int num;
		cin >> num;
		if (num <= m) {
			coins[num]++;
		}
	}

	if (findCoins(m)) {
		bool first = true;
		while (!res.empty()) {
			if (first) {
				first = false;
			}
			else {
				cout << " ";
			}
			cout << res.top();
			res.pop();
		}
	}
	else {
		cout << "No Solution";
	}
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
最少硬币问题是指在给定面额的硬币中,找出能够组成指定金额的最少硬币数。可以使用动态规划来解决这个问题。 以下是用Java实现最少硬币问题的示例代码: ```java public class MinimumCoins { public static int minCoins(int[] coins, int amount) { int[] dp = new int[amount + 1]; Arrays.fill(dp, Integer.MAX_VALUE); dp[0] = 0; for (int i = 1; i <= amount; i++) { for (int j = 0; j < coins.length; j++) { if (coins[j] <= i && dp[i - coins[j]] != Integer.MAX_VALUE) { dp[i] = Math.min(dp[i], dp[i - coins[j]] + 1); } } } return dp[amount] == Integer.MAX_VALUE ? -1 : dp[amount]; } public static void main(String[] args) { int[] coins = {1, 2, 5}; int amount = 11; int minCoins = minCoins(coins, amount); System.out.println("Minimum coins required to make " + amount + " is " + minCoins); } } ``` 在上面的代码中,我们使用一个数组dp来存储每个金额所需的最少硬币数。我们首先将dp数组初始化为Integer.MAX_VALUE,然后将dp[0]设置为0,因为组成0元需要0枚硬币。 接下来,我们使用两个嵌套循环来遍历每个金额和每个硬币面额。如果当前硬币面额小于等于当前金额,并且使用当前硬币面额可以组成金额i - coins[j],那么我们更新dp[i]为dp[i - coins[j]] + 1的最小值。最终,dp[amount]存储了组成指定金额所需的最少硬币数。如果dp[amount]等于Integer.MAX_VALUE,则表示无法组成指定金额,返回-1。 在上面的示例中,我们使用coins数组存储硬币面额,amount变量存储指定金额。输出结果为“Minimum coins required to make 11 is 3”,表示组成11元需要3枚硬币,即1枚5元硬币和2枚2元硬币。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值