📜  硬币找零的Java程序

📅  最后修改于: 2022-05-13 01:58:09.405000             🧑  作者: Mango

硬币找零的Java程序

给定一个 N 值,如果我们想用 N 美分找零,并且我们有无限供应 S = { S1, S2, .. , Sm} 价值的硬币,我们可以用多少种方法来找零?硬币的顺序无关紧要。

例如,对于 N = 4 和 S = {1,2,3},有四种解:{1,1,1,1},{1,1,2},{2,2},{1, 3}。所以输出应该是 4。对于 N = 10 和 S = {2, 5, 3, 6},有五种解决方案:{2,2,2,2,2},{2,2,3,3}, {2,2,6}、{2,3,5} 和 {5,5}。所以输出应该是5。

Java
/* Dynamic Programming Java implementation of Coin
   Change problem */
import java.util.Arrays;
  
class CoinChange
{
    static long countWays(int S[], int m, int n)
    {
        // Time complexity of this function: O(mn)
  
        // table[i] will be storing the number of solutions
        // for value i. We need n+1 rows as the table is
        // constructed in bottom up manner using the base
        // case (n = 0)
        long[] table = new long[n+1];
  
        // Initialize all table values as 0
        Arrays.fill(table, 0);   //O(n)
  
        // Base case (If given value is 0)
        table[0] = 1;
  
        // Pick all coins one by one and update the table[]
        // values after the index greater than or equal to
        // the value of the picked coin
        for (int i=0; i