Advertisement
ogv

Untitled

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