Leetcode 322 Coin Change (full backpack)

Source: Internet
Author: User

You is given coins of different denominations and a total amount of money amount. Write a function to compute the fewest number of coins so need to make up that amount. If that amount of cannot is made up by any combination of the coins, return-1.

Example 1:
Coins = [1, 2, 5], amount = 11
Return 3 (11 = 5 + 5 + 1)

Example 2:
Coins = [2], amount = 3
Return-1.

Note:
You may assume so you have a infinite number of each kind of coin.


Title Link: https://leetcode.com/problems/coin-change/

Title Analysis: Because the number is infinite, so it is a complete knapsack count problem, dp[i] means the minimum number required to close to I, DP initialized to infinity, dp[0] = 0

public class Solution {public
    
    int coinchange (int[] coins, int amount) {
        int[] dp = new Int[amount + 1];
        Arrays.fill (DP, integer.max_value);
        Dp[0] = 0;
        for (int i = 0; i < coins.length; i + +) {for
            (int j = 0; J <= Amount; j + +) {
                int pre = j-coins[i];
                if (pre >= 0 && Dp[pre] < Integer.max_value) {
                    Dp[j] = Math.min (Dp[j], Dp[pre] + 1);}}}
        if (dp[amount] = = integer.max_value) {
            return-1;
        }
        return dp[amount];
    }
}


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.