将数量分成硬币,镍币和硬币递归

时间:2014-01-27 22:16:10

标签: java recursion

我写了以下代码:

public class CoinChange
{
    static int n = 0;
    static int count = 0; 
    public static void main (int value) {
        n = value;
        recursiveLoop(0, 0, 0, 0);
    }        
    private static int recursiveLoop(int i, int j, int k, int l)
    {
        if ((i + (5 * j) + (10 * k) + (25 * l)) == n)
            count ++;
        l++;
        if (l > n / 25)
        {
            l = 0;
            k++;
        }
        if (k > n / 10)
        {
            k = 0;
            j++;
        }

        if (j > n / 5)
        {
            j = 0;
            i++;
        }  
        if (i>n)
        { 
            System.out.println("Number ways " + n + 
            " can be changed is " + count + ".");
            System.exit(0);
        } 
        recursiveLoop(i, j, k, l);
        return count;
    }
}

此代码工作正常至50美分但是当我输入大于50时,我收到堆栈溢出错误。请帮我识别这个程序的问题。

2 个答案:

答案 0 :(得分:1)

您的唯一回报是在递归调用之后。这意味着您当前的程序永远不会突破递归。您需要检查“完成”条件,如果“完成”为真,则返回。或者,将recursiveLoop(i, j, k, l);置于if声明之下。

答案 1 :(得分:0)

Clear[change]
units = {10000, 5000, 2000, 1000, 500, 100, 25, 10, 5, 1};
names = {"$100", "$50", "$20", "$10", "$5", "$1", "quarter", "dime", 
   "nickel", "penny"};
toUnit = Dispatch@Thread[units -> names];
fromUnit = Dispatch@Thread[names -> units];
change[0] := Sequence[]
change[n_Integer?Positive] := 
 change[n] = Module[{large = Max@Cases[units, x_ /; x <= n], t},
   Flatten@{ConstantArray[large /. toUnit, t = Floor[n/large]], 
     change[n - t large]}
   ]
Total /@ (Array[change, lim = 100000] /. fromUnit) == Range[lim]

Tally@Flatten@Array[change, 1000]