无限背包:leecode322. 零钱兑换

给你一个整数数组 coins ,表示不同面额的硬币;以及一个整数 amount ,表示总金额。

计算并返回可以凑成总金额所需的 最少的硬币个数 。如果没有任何一种硬币组合能组成总金额,返回 -1 。

你可以认为每种硬币的数量是无限的。

示例 1:

输入:coins = [1, 2, 5], amount = 11
输出:3 
解释:11 = 5 + 5 + 1
示例 2:

输入:coins = [2], amount = 3
输出:-1
示例 3:

输入:coins = [1], amount = 0
输出:0
 

提示:

1 <= coins.length <= 12
1 <= coins[i] <= 231 - 1
0 <= amount <= 104

使用记忆化搜索:

class Solution {

    public  int coinChange(int[] arr, int account) {
        int[][] cache = new int[arr.length][account+1];
        for (int i = 0; i < cache.length; i++) {
            for (int j = 0; j < account+1; j++) {
                cache[i][j] = -1;
            }
        }
        int r = dfs(arr, 0, account, cache);
        return r >= 99999 ? -1 : r;
    }

    public  int dfs(int[] arr, int start, int rest, int[][] cache) {
        if (rest < 0) {
            return 999999;
        }
        if (rest == 0) {
            return 0;
        }
        if (start >= arr.length) {
            return 99999;
        }
        if (cache[start][rest] == -1) {
            //选当前数字,不移动
            int r1 = 1+dfs(arr, start , rest - arr[start], cache);
            //不选当前数字,往后移动1位
            int r2 = dfs(arr, start + 1, rest, cache);
            int r = Math.min(r1, r2);
            cache[start][rest] = r;
        }
        return cache[start][rest];
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值