322. Coin Change Java Solutions

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.

Credits:
Special thanks to @jianchao. Li.fighter for adding the problem and creating all test cases.

Where Ans[i] represents the amount of money for the minimum number of coins when the change, the recursive type is:

Ans[i] = Math.min (Ans[i], Ans[i-coins[j]] + 1);

Where Coins[j] is the first J-coin, and i-coins[j] is the sum of money I minus the value of one of the coins, the remaining amount of money in the ANS array to find the value, and then add 1 and the current ANS array of values to compare, take the smaller one update ans array.

1  Public classSolution {2      Public intCoinchange (int[] coins,intamount) {3         int[] ans =New int[Amount+1];4Arrays.fill (ans,amount+1);5Ans[0] = 0;6          for(inti = 1; i < ans.length; i++){7              for(intj = 0; J < Coins.length; J + +){8                 if(Coins[j] <=i)9Ans[i] = math.min (ans[i],ans[i-coins[j]]+1);Ten             } One         } A         returnAns[amount] = = (amount+1)? -1: Ans[amount]; -     } -}

322. Coin Change Java Solutions

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.