问:帮我解决以下问题的逻辑:
您将获得两行的文件。第一行将包含两个由逗号分隔的整数(例如X,Y)。在下一行中,将再次用逗号分隔Y个整数。您应该能够输出Y个整数(整数可以无限次使用)的所有可能组合,这些加法将得到值X
答:问题定义
在硬币兑换问题中,您可以想到一家银行的硬币自动售货机,其硬币供应充足,可以将硬币返还给人们以换成人们投入的纸币,在这种情况下,该机器将退回硬币,其总金额为将相同的值放入机器,这里的顺序无关紧要(即{1,2,2},{2,1,2},{2,2,1}将被视为相同)。
现在的问题是,您必须找到可以执行此操作的解决方案总数。
例如 :
假设机器有1、2、3卢比硬币的无限量供应。
一个人来,要兑换5卢比的钞票。
现在,机器可以以
{1,1,1,1,1}硬币
{1,1,1,2}硬币
{1,2,2}硬币
{5}
因此,有4种方法可以做到这一点。
package com.tech.blog;
import java.util.Scanner;
public class CoinExchangeProblem {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n;
int x;
int y;
int sum;
//Final sum of the value in return of which coins are being given
System.out.print("Enter the final sum to be formed using coins : ");
sum = sc.nextInt();
//For the count of set of coins ( count of different values of coins )
System.out.print("Enter total number of coins : ");
n = sc.nextInt();
int[] coin = new int[n];
// To input the values of coins for our problem
System.out.print("Enter values of coins : ");
for (int i = 0; i < n; i++)
coin[i] = sc.nextInt();
sc.close();
// We need sum + 1 rows as the table is constructed in bottom up manner using
// the base case 0 value case (n = 0)
int[][] solution = new int[sum + 1][n];
//Base case fill all the entries for 0 value case (n = 0)
for (int i = 0; i < n; i++)
solution[0][i] = 1;
// Filling the table entries in bottom up manner
for (int i = 1; i < sum + 1; i++) {
for (int j = 0; j < n; j++) {
// number of solutions including coin[j]
x = (i - coin[j] >= 0) ? solution[i - coin[j]][j] : 0;
// number of solutions excluding coin[j]
y = (j >= 1) ? solution[i][j - 1] : 0;
// total number of solution
solution[i][j] = x + y;
}
}
System.out.println("Total solutions for your problem is "
+ solution[sum][n - 1]);
return;
}
}
上面代码的输出
Enter the final sum to be formed using coins :4
Enter total number of coins :3
Enter values of coins :123
Total solutions for your problem is 4