Coin Changes LeetCode

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

Example 1:

Input: coins = [1, 2, 5], amount = 11
Output: 3 
Explanation: 11 = 5 + 5 + 1

Example 2:

Input: coins = [2], amount = 3
Output: -1

Note:
You may assume that you have an infinite number of each kind of coin.

Accepted
384,527
Submissions
1,108,726

 

class Solution {
    public int coinChange(int[] coins, int amount) {
        
        
        Arrays.sort(coins);
        
        int dp[] = new int[amount+1];
        
        //initial assign 
        
        for(int i = 1; i<=amount; i++){
            dp[i] =Integer.MAX_VALUE;
        }
        
        dp[0]=0;
        
        //dp[i] = min{ dp[i-coins[0]]+1, dp[i-coins[1]]+1, dp[i-coins[2]]+1, ... dp[i- coins[coins.length]]+1 }
        for(int i = 1; i<= amount; i++){
            
            for(int j = 0; j< coins.length; j++){
                
                if(i>=coins[j]&& dp[i-coins[j]]!=Integer.MAX_VALUE){
                    
                    dp[i] = Math.min(dp[i-coins[j]]+1,dp[i]);
                }
            }
        
        }
        
        if(dp[amount]==Integer.MAX_VALUE){
            dp[amount]=-1;
        }
        
        return dp[amount];
    }
}

 

posted @ 2020-06-08 15:45  CodingYM  阅读(154)  评论(0编辑  收藏  举报