leetcode322. Coin Change

换硬币问题,经典DP问题,我们依然可以采取带记忆数组的递归或者动态规划来求解问题。同样地,这是一道经典的完全背包题目,可以和leetcode322对照着看,注意体会细节。

public  int coinChange(int[] coins, int amount) {
       int[] dp = new int[amount + 1];
        Arrays.fill(dp, amount + 1);
        dp[0] = 0;
        for (int i = 1; i <= coins.length; i++) {
            for (int j = 0; j <= amount; j++) {
                if (j >= coins[i - 1]) {
                    dp[j] = Math.min(dp[j], dp[j - coins[i - 1]] + 1);
                }
            }
        }
        return dp[amount] == amount + 1 ? -1 : dp[amount];
    }

你可能感兴趣的:(leetcode322. Coin Change)