11 wk-Dynamic programming-coin Change

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 = one
return 3 (one = 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.
  
Ideas

Given a number of coins of different value, assuming that the number of each coin is infinite, given a specific value, it is necessary to ask whether the value can be obtained with these combinations of coins, if the number of coins with the fewest use can be given.
Using dynamic programming, from 1 to the given value, amount the minimum number of coins that can be used to get that value. Source Code

class Solution {public:int Coinchange (vector<int>& coins, int amount) {  
        int a[10000];  
        int i,j,t;  
        for (i = 1;i <= amount;i + +) A[i] =-1;  
        A[0] = 0; for (i = 1;i <= amount;i + +) {for (j = 0;j < Coins.size (); j + +) {if ((i-coins[j))  
                    = 0 && a[i-coins[j]] >= 0) {t = A[i-coins[j]] + 1;  
                if (a[i] = =-1 | | a[i] > t) a[i] = t;  
    }}} return A[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.