[Leetcode] Coin Change

Source: Internet
Author: User

Coin Change

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.

Dp!

`1 classSolution {2  Public:3     intCoinchange (vector<int>& coins,intamount) {4vector<int> dp (amount +1, Int_max);5dp[0] =0;6          for(Auto coin:coins) {7              for(inti = coin; I <= amount; ++i) {8                 if(Dp[i-coin]! =Int_max) {9Dp[i] = min (Dp[i], Dp[i-coin] +1);Ten                 } One             } A         } -         returnDp[amount] = = Int_max? -1: Dp[amount]; -     } the};`

[Leetcode] Coin Change

Related Keywords:

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.