改变制作算法

时间:2014-01-27 15:22:33

标签: java algorithm

一个典型的变化问题,但有点扭曲。鉴于给定的金额和面额很大,我需要提出使用RECURSION可以赚取金额的总方式。该功能的签名如下

int makeChange(int Amount, int[] Denominations)

金额 - 总金额

衡量单位 - 可用的denominatins。

它返回总路数。确保必须使用递归...

1 个答案:

答案 0 :(得分:4)

关键的想法是要了解每个点你有两个选择:

  1. 使用您正在查看的当前硬币,并在从amount减去它时递归。
  2. 请勿使用它,并使其无法供以后选择。
  3. 该函数应返回(1)和(2)的总和。

    的伪代码:

    makeChange(amount,Denominations):
       //stop clauses:
       if (amount == 0) return 1
       if (amount < 0) return 0
       i <- first index of Denominations where Denominations[i] is not zero
       if there is no such i (all are zero):
            return 0
       num1 = makeChange(amount-Denominations[i],Denominations) //recursive call, using Denominations[i]
       temp <- Denominations[i]
       Denominations[i] = 0
       num2 = makeChange(amount,Denominations) //recursive call, not using Denominations[i] - and will never do again
       Denominations[i] = temp //setting environment back to original
       return num1+num2
    

    java代码:

    public static int makeChange(int amount, int[] d) { 
        if (amount < 0) return 0;
        if (amount == 0) return 1;
        int i = 0;
        for (i = 0; i < d.length; i++) { 
            if (d[i] != 0) break;
        }
        if (i == d.length) return 0;
        int num1 = makeChange(amount-d[i],d);
        int temp = d[i];
        d[i] = 0;
        int num2 = makeChange(amount,d);
        d[i] = temp;
        return num1 + num2;
    }