代码随想录算法训练营第三十九天|518. 零钱兑换 II

518. 零钱兑换 II

public static int coinChange(int[] coins, int amount) {
    // 找出最后一步
    // 定义损失函数 定义记忆化存储基本单元
    // 状态转移方程 f(n) = f[n-1] +
    // Min(f(n) = f(n-coins[i])+f(coins[i]));
    // 边界 (递归过程中需要判断)
    // 初始化 (在未递归之前需要处理)
    // 返回答案
    int INF = (Integer.MAX_VALUE / 4);
    int[] dp = new int[amount + 1];

    for (int i = 1; i <= amount; i++) {
        dp[i] = INF;
    }
    dp[0] = 0;
    for (int i = 0; i <= amount; i++) {
        for (int j = 0; j < coins.length; j++) {
            if (amount >= coins[j] && coins[j] + i < amount + 1 && coins[j] + i >= 0) {
                dp[i + coins[j]] = Math.min(dp[i + coins[j]], dp[i] + 1);
            }
        }


    }

    return dp[amount] >= INF ? -1 : dp[amount];

}

public static int findCoins(int[] dp, int[] coins, int amount) {
    int changeNumber = -1;
    if (amount - coins[0] >= 0 && dp[amount - coins[0]] != -1) {
        changeNumber = dp[amount - coins[0]] + dp[coins[0]];
    } else {
        return -1;
    }
    for (int i = 0; i < coins.length; i++) {
        if (amount - coins[i] < 0) {
            return changeNumber;
        }
        if (changeNumber > dp[amount - coins[i]] + dp[coins[i]] && coins[i] != -1) {
            changeNumber = dp[amount - coins[i]] + dp[coins[i]];
        }

    }
    return changeNumber;

}

你可能感兴趣的:(算法,动态规划)