0
点赞
收藏
分享

微信扫一扫

Believing Process 力扣Hot322. 零钱兑换 DFS+记忆搜索

两岁时就很帅 2022-02-20 阅读 33
leetcodedfs
package MidTest;
public class 零钱兑换 {
    public static void main(String[] args) {
        int[]  coins = {186,419,83,408};
        int amount = 6249;
        System.out.println(coinChange(coins,amount));
    }
    static int[] memo;
    public static int coinChange(int[] coins, int amount) {
        if(coins.length==0) return -1;
        memo = new int[amount];
        return findway(coins,amount);
    }

    private static int findway(int[] coins, int amount) {
        if(amount<0) return -1;
        if(amount==0) return 0;
        //如果当前amount的数在memo数组中出现过,直接调用。为什么下标是amount-1,因为数组从0开始啊,笨逼
        if(memo[amount-1]!=0) return memo[amount-1];
        int min = Integer.MAX_VALUE;
        for (int i = 0; i < coins.length; i++) {
            int res = findway(coins,amount-coins[i]);
            if(res>=0&&res<min){
                min = res+1;
            }
        }
        memo[amount-1] = min==Integer.MAX_VALUE?-1:min;
        return memo[amount-1];
    }


}

         findway函数返回的是当前amount所需的硬币数(其实就是返回的memo数组中的值),-1则是无法用该硬币数组组成amount。

         memo数组是用于递归中的记忆数组,memo[amount-1]表示amount所需的硬币数,当在递归中重复出现相同的amount时,就可以直接调用。

        min=res+1是加上最后一次findway返回0时(即amount=0)兑换的那枚硬币。

举报

相关推荐

0 条评论