java算法 硬币
如果我们有面值为1元、3元和4元的硬币若干枚,
如何用最少的硬币凑够x元?
从终端输入一个整数,
输入最少要多少枚硬币凑出这个整数?
import java.util.Scanner; public class Coins { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int[] coins = {1,3,4}; int value = sc.nextInt(); int[] answer = new int[value]; int min = new Coins().solve(coins, value, answer); for(int i = value-1;i>=0;){ System.out.println(answer[i]); i=i-answer[i]; } System.out.println("最小数量:"+min); } public int solve(int[] coins,int value,int[] answer){ int[] mins = new int[value+1]; mins[0]=0; for(int i=1;i<=value;i++) mins[i]=Integer.MAX_VALUE; for(int i=1;i<=value;i++){ for(int j=0;j<coins.length;j++){ if(coins[j]<=i&&mins[i]>mins[i-coins[j]]+1){ mins[i]=mins[i-coins[j]]+1; answer[i-1]=coins[j]; } } } return mins[value]; } }