Algorithm to determine coin combinations

后端 未结 13 2635
臣服心动
臣服心动 2020-12-25 08:33

I was recently faced with a prompt for a programming algorithm that I had no idea what to do for. I\'ve never really written an algorithm before, so I\'m kind of a newb at t

13条回答
  •  心在旅途
    2020-12-25 08:48

    Here's a recursive solution in Java:

    // Usage: int[] denoms = new int[] { 1, 2, 5, 10, 20, 50, 100, 200 };       
    // System.out.println(ways(denoms, denoms.length, 200));
    public static int ways(int denoms[], int index, int capacity) {
        if (capacity == 0) return 1;
        if (capacity < 0 || index <= 0 ) return 0;
        int withoutItem = ways(denoms, index - 1, capacity); 
        int withItem = ways(denoms, index, capacity - denoms[index - 1]); 
        return withoutItem + withItem;
    }
    

提交回复
热议问题