Created
July 21, 2017 07:15
-
-
Save benyblack/26ed1fac14202d3080cc33e080b91076 to your computer and use it in GitHub Desktop.
Minimum Coin Change
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
public class Solution { | |
public int CoinChange(int[] coins, int amount) { | |
if (amount == 0) return 0; | |
if(coins.Length==1){ | |
if(amount%coins[0]==0) | |
return amount/coins[0]; | |
else | |
return -1; | |
} | |
var r = cc(coins,amount,new Dictionary<int,int>()); | |
if(r==int.MaxValue) | |
return -1; | |
return r; | |
} | |
public int cc(int[] coins, int amount,Dictionary<int,int> dic) { | |
if (amount == 0) return 0; | |
if(dic.ContainsKey(amount)){ | |
return dic[amount]; | |
} | |
int res = int.MaxValue; | |
int n = coins.Length; | |
for (int i=0; i<n; i++) | |
{ | |
if (coins[i] <= amount) | |
{ | |
int subRes = cc(coins, amount-coins[i],dic); | |
if (subRes!= int.MaxValue && subRes + 1 < res) | |
res = subRes + 1; | |
} | |
} | |
dic.Add(amount,res); | |
return res; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment