【发布时间】:2015-09-20 16:06:41
【问题描述】:
我一直在使用动态编程解决硬币找零问题。我试图创建一个数组 fin[] ,其中包含该索引所需的最少硬币数量,然后打印它。 我写了一个我认为应该给出正确输出的代码,但我不知道为什么它没有给出准确的答案。 例如:对于输入:4 3 1 2 3 (4 是要找零的数量,3 是可用硬币类型的数量,1 2 3 是硬币值的列表) 输出应该是:0 1 1 1 2(因为我们有 1,2,3 作为可用硬币,它需要 0 个硬币来改变 0,1 个硬币来改变 1,1 个硬币来改变 2,1 个硬币来改变 3 和 2硬币兑换 4) 但它给出了 0 1 2 2 2
代码如下:
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
Scanner in= new Scanner(System.in);
int ch = in.nextInt();
int noc = in.nextInt();
int[] ca = new int[noc];
for(int i=0;i<noc;i++)
{
//taking input for coins available say a,b,c
ca[i] = in.nextInt();
}
int[] fin = new int[ch+1]; //creating an array for 0 to change store the minimum number of coins required for each term at index
int b=ch+1;
for(int i=0;i<b;i++)
{
int count = i; //This initializes the min coins to that number so it is never greater than that number itself. (but I have a doubt here: what if we don't have 1 in coins available
for(int j=0; j<noc; j++)
{
int c = ca[j]; //this takes the value of coins available from starting everytime i changes
if((c < i) && (fin[i-c] +1 < count)) // as we using dynamic programming it starts from base case, so the best value for each number i is stored in fin[] , when we check for number i+1, it checks best case for the previous numbers.
count = fin[i-c]+1 ;
}
fin[i]= count;
}
for(int i=0;i<b;i++)
{
System.out.println(fin[i]);
}
}
}
我参考了这个页面:http://interactivepython.org/runestone/static/pythonds/Recursion/DynamicProgramming.html
谁能帮忙?
【问题讨论】:
-
请解释输入和输出背后的含义,以及为什么您的预期输出是这样的。
-
一个解释什么是“硬币变化”问题的链接会有所帮助......有代码但没有解释这个代码应该做什么:/
-
有什么问题?
标签: java dynamic-programming coin-change