Advertisement
ogv

Untitled

ogv
Aug 12th, 2019
226
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.18 KB | None | 0 0
  1. class Solution {
  2.     public int coinChange(int[] coins, int amount) {
  3.         if (coins.length == 0 ) return amount > 0 ? -1: 0;
  4.         if (amount == 0) return 0;
  5.        
  6.         int[] cache = new int[amount + 1];
  7.         return change(coins, cache, amount);
  8.     }
  9.    
  10.     private int change(int[] coins, int[] cache, int amount) {
  11.         if (cache[amount] != 0) {
  12.             return cache[amount];
  13.         }
  14.        
  15.         int result = -1;
  16.         int candidate;
  17.        
  18.         for (int i = 0; i < coins.length; i++) {
  19.             if (amount < coins[i]) {
  20.                 continue;
  21.             }
  22.                        
  23.             int rest = amount - coins[i];
  24.                            
  25.             if (rest > 0) {
  26.                 int restCount = change(coins, cache, rest);
  27.                
  28.                 candidate = (restCount > 0) ? restCount + 1: -1;                
  29.             } else {
  30.                 candidate = 1;
  31.             }
  32.            
  33.             if (candidate != -1 && (candidate < result || result == -1)) {
  34.                 result = candidate;
  35.             }
  36.         }
  37.        
  38.         cache[amount] = result;
  39.         return result;
  40.     }
  41. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement