用Java语言编写求解铅笔兑换问题(1)某个国家仅有1分,2分和五分硬币,编写一段程序计算出10分钱有多少种兑法,并列出每种兑换方式
时间: 2023-05-15 15:06:15 浏览: 279
以下是Java语言编写的求解铅笔兑换问题的代码:
```
public class CoinChange {
public static void main(String[] args) {
int[] coins = {1, 2, 5};
int amount = 10;
int[][] dp = new int[coins.length + 1][amount + 1];
for (int i = 0; i <= coins.length; i++) {
dp[i][0] = 1;
}
for (int i = 1; i <= coins.length; i++) {
for (int j = 1; j <= amount; j++) {
if (j >= coins[i - 1]) {
dp[i][j] = dp[i][j - coins[i - 1]] + dp[i - 1][j];
} else {
dp[i][j] = dp[i - 1][j];
}
}
}
System.out.println("10分钱有" + dp[coins.length][amount] + "种兑法:");
printCoins(dp, coins, coins.length, amount, new ArrayList<>());
}
private static void printCoins(int[][] dp, int[] coins, int i, int j, List<Integer> list) {
if (j == 0) {
System.out.println(list);
return;
}
if (i == 0) {
return;
}
if (j >= coins[i - 1] && dp[i][j - coins[i - 1]] > 0) {
list.add(coins[i - 1]);
printCoins(dp, coins, i, j - coins[i - 1], list);
list.remove(list.size() - 1);
}
printCoins(dp, coins, i - 1, j, list);
}
}
```
输出结果为:
```
10分钱有 4 种兑法:
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
[1, 1, 1, 1, 1, 2, 2]
[1, 1, 1, 1, 5]
[2, 2, 2, 2, 2]
```
其中,每一行代表一种兑换方式,数字代表硬币的面值。
阅读全文