class="hide-preCode-box">

上面是对时间复杂度进行优化,下面对空间进行优化,考虑到dp[i][j]只跟dp[i-1]和dp[i]有关,我们可以把二维降成一维,代码如下所示:

public class Solution3 {

    /**
     * 求找零钱最小硬币数
     *
     * @param coins 硬币面值集合
     * @param total 找零钱总数
     * @return 最少硬币数
     */
    public int minCoins(int[] coins, int total) {
        int[] dp = new int[total + 1];
        //注意下这里的值不能初始化为Integer.MAX_VALUE,因为相加会出现整数溢出
        Arrays.fill(dp,Integer.MAX_VALUE - total);
        dp[0] = 0;
        for (int i = 1; i <= coins.length; i++) {
            for (int j = coins[i-1]; j <= total; j++) {
                dp[j] = Math.min(dp[j], dp[j - coins[i - 1]] + 1);
            }
        }
        return dp[total];
    }

    public static void main(String[] args) {
        int[] coins = new int[]{2, 3, 5};
        int total = 12;
        Solution3 solution = new Solution3();
        System.out.println(solution.minCoins(coins, total));
    }
}
 class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"> class="hide-preCode-box">

五、执行结果

在这里插入图片描述

>>
注:本文转载自blog.csdn.net的仁者乐山智者乐水的文章"https://blog.csdn.net/qq_39559641/article/details/117172758"。版权归原作者所有,此博客不拥有其著作权,亦不承担相应法律责任。如有侵权,请联系我们删除。
复制链接

评论记录:

未查询到任何数据!