Last active
September 22, 2022 19:02
-
-
Save dluciano/d39b0cb34a43ba81441f64cda0a96c4e to your computer and use it in GitHub Desktop.
322. 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
public class Solution { | |
public int CoinChange(int[] coins, int amount){ | |
var dp = new int[amount + 1]; | |
Array.Fill(dp, int.MaxValue); | |
dp[0] = 0; | |
foreach(var coin in coins){ | |
for(var change = 1; change <= amount; change++){ | |
if(coin > change || dp[change - coin] == int.MaxValue) | |
continue; | |
dp[change] = Math.Min(dp[change], 1 + dp[change - coin]); | |
} | |
} | |
return dp[dp.Length - 1] == int.MaxValue ? -1 : dp[dp.Length - 1]; | |
} | |
public int CoinChangeRec(int[] coins, int amount) { | |
var memo = new int?[amount]; | |
int CountDp(in int n){ | |
if(n == 0) | |
return 0; | |
if(n < 0) | |
return -1; | |
if(memo[n - 1].HasValue) | |
return memo[n - 1].Value; | |
var counter = int.MaxValue; | |
foreach(var coin in coins) { | |
var current = CountDp(n - coin); | |
if(current >= 0 && current < counter) | |
counter = Math.Min(counter, 1 + current); | |
} | |
memo[n - 1] = counter == int.MaxValue ? -1 : counter; | |
return memo[n - 1].Value; | |
} | |
var res = CountDp(amount); | |
return res == int.MaxValue ? -1 : res; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment