我们有无限数量的硬币,每个硬币都有一定价值。您能算出所需的最小硬币数量,以便硬币总和达到一定的要求值吗?我们将使用动态编程来解决这个问题。
但是,如果我想知道使用哪种硬币以及使用了多少次,我该怎么做?
我尝试了此操作,但它没有为我提供正确的输入。
int findForYes(vector<int> coins,int V,int coinNumber[M][N])
{
if (V == 0) return 0;
int res = INT_MAX;
for (int i=0; i<coins.size(); i++)
if (coins[i] <= V)
{
int sub_res = findForYes(coins, V-coins[i]);
if (sub_res != INT_MAX && sub_res + 1 < res)
{
res = sub_res + 1;
coinNumber[V][coins[i]]++;
}
}
return res;
}
coinNumber [M] [N]代表具有所有N个硬币的M的总和,V代表要获得的总和。
假设硬币为[10,5,15],我们必须进行25的更改,然后组合之一是1乘以10、0乘以5和1乘以15,因此输出应为[1、0、5、5 ]
答案 0 :(得分:0)
因此,据我了解,您想解决CoinChange问题,但不仅要返回组合数量所需的最小数量的硬币,而且还要返回硬币本身。 我用Java写过东西,希望对您有所帮助。
public int coinChange(int []个硬币,int数量){ 如果(硬币== null ||金额<0)返回-1; int [] dp = new int [amount + 1]; // dp [i] =我们需要创建i sum的最小数量。 Arrays.fill(dp,数量+1); //用amount + 1初始化数组; dp [0] = 0;
List<List<Integer>> lst = new ArrayList<>(); // lst(i) will contain the minimal combination of coins that sums to i.
lst.add(new ArrayList<>()); // add the combination for 0
for (int i = 1; i <= amount; i++) {
List<Integer> currentCoinCombination = new ArrayList<>();
for (int coin : coins) {
if (i - coin < 0) continue;
if (dp[i-coin] < dp[i]){
dp[i] = dp[i - coin] + 1;
currentCoinCombination = new ArrayList<>(lst.get(i-coin));
currentCoinCombination.add(coin);
}
}
lst.add(currentCoinCombination);
}
return dp[amount] == amount + 1 ? -1 : dp[amount];
}
请记住,您要寻找的硬币组合将位于lst.get(amount);