algorithm - 为什么以下获取最低硬币找零不起作用

标签 algorithm

我正在尝试编写代码来找到最小数量的硬币来进行更改。这是我的代码:

public class MinCoinsToChange {
    //private static int q=Integer.MAX_VALUE;

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        System.out.println(getmin(new int [] {1,2,3},5));
    }

    static int getmin(int [] C,int P) {
        int q = Integer.MAX_VALUE;
        if(P <= 0)
        {
            return q;
        }
        for(int i = 0; i < C.length; i++)
            q = Math.min(q, getmin(C, P - C[i]));
        return q;
    }
}

但是代码不工作。我犯的错误在哪里?

最佳答案

我可以改正错误。这里是更正

        int q=Integer.MAX_VALUE;
    if(P<=0)
    {
        q=0;
        return q;
    }
    for(int i=0;i<C.length;i++)
        q= Math.min(q, 1+getmin(C, P-C[i]));
    return q;
}

关于algorithm - 为什么以下获取最低硬币找零不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28653157/

相关文章:

c - 高尔夫锦标赛配对算法

c++ - 使用 std::fill 填充多维数组的安全方法是什么?

algorithm - 直线上给出的点的最短距离对?

javascript - 在 Javascript 中比较两个对象数组与文字值的更快方法

algorithm - 为什么在 matlab 中 orth 函数比 qr 慢得多?

algorithm - 积分最多的段算法分析

algorithm - 有没有办法从情节中读取数据?

javascript - leetcode 3sum 帮助,我该如何优化这个答案?

algorithm - 如何找到棋盘上两点之间的最短路径?

c++ - 像钻石一样的信号量