Advertisement
ogv

Untitled

ogv
Aug 12th, 2019
116
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.08 KB | None | 0 0
  1. /*
  2. Runtime: 26 ms, faster than 20.24% of Java online submissions for Coin Change. :-(
  3. Memory Usage: 36 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.         for (int i = 0; i < coins.length; i++) {
  21.             int rest = amount - coins[i];
  22.             if (rest > 0) {
  23.                 int num = change(coins, cache, rest);
  24.                 if (num != -1 && (num < result || result == -1)) {
  25.                     result = num + 1;
  26.                 }
  27.             } else if (rest == 0) {
  28.                 result = 1;
  29.             }
  30.         }
  31.        
  32.         cache[amount] = result;
  33.         return result;
  34.     }
  35. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement