322. Coin Change

Source: Internet
Author: User

ref:https://leetcode.com/problems/coin-change/

is a complete knapsack problem, you can review the knapsack problem again.

01 Backpack:

For each item

For Amount...cost[item]

F[V] = Max{f[v], F[v-cost[item]] + Weight[item]}

Because 01 backpack each item can only be used once, so amount to calculate from the back forward, because the comparison of the time with F[v] and F[v-cost[item]], the second there is a minus, so back to calculate, the result is not used in front of

Full backpack

For each item

For Cost[item]...amout

F[V] = Max{f[v], F[v-cost[item]] + Weight[item]}

Because each item can be used many times, so amount from small to large walk, because every time after the results are used in the previous results.

If you require a full backpack, set f[0] to 0 and the others to Integer.min_value

The topic is discussed below, the question is a complete knapsack problem, coins[] is Cost[],amount is the capacity of the backpack, asked the backpack just full, weight is all the item is 1

The difference is that the traditional knapsack problem is to ask for the maximum weight, but the topic is to seek the minimum weight, so there are differences in initialization. Dp[0] = 0, and all that remains is integer.max_value.

1      Public intCoinchange (int[] coins,intamount) {2         if(Coins.length = = 0 | | Amount < 0) {3             return-1;4         }5         int[] DP =New int[Amount+1];6 Arrays.fill (DP, integer.max_value);7Dp[0] = 0;8          for(inti = coins.length-1; I >= 0; i--) {9              for(intj = Coins[i]; J <= Amount; J + +) {Ten                 if(Dp[j-coins[i]]! =integer.max_value) { OneDP[J] = Math.min (Dp[j], Dp[j-coins[i]] + 1); A                 } -             } -         } the         returnDp[amount] = = Integer.max_value? -1: Dp[amount]; -}

322. Coin Change

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.