generated from eyamenko/dotnet-template-repository
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProblem46.cs
More file actions
61 lines (51 loc) · 1.81 KB
/
Problem46.cs
File metadata and controls
61 lines (51 loc) · 1.81 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
namespace LeetCode;
/// <summary>
/// <see href="https://leetcode.com/problems/coin-change/">Coin Change</see>.
/// </summary>
public static class Problem46
{
/// <summary>
/// You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money.
/// Return the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1.
/// You may assume that you have an infinite number of each kind of coin.
/// Time complexity: O(n * a).
/// Space complexity: O(n + a).
/// </summary>
/// <param name="coins">Coins.</param>
/// <param name="amount">Amount.</param>
/// <returns>Fewest number of coins that is needed to make up the amount.</returns>
public static int CoinChange(int[] coins, int amount)
{
var results = new int[amount];
return Traverse(coins, amount, results);
}
private static int Traverse(int[] coins, int amount, int[] results)
{
if (amount == 0)
{
return 0;
}
var index = amount - 1;
if (results[index] != 0)
{
return results[index];
}
var minCoins = int.MaxValue;
for (var i = 0; i < coins.Length; i++)
{
if (coins[i] <= amount)
{
var subResult = Traverse(coins, amount - coins[i], results);
if (subResult >= 0)
{
minCoins = Math.Min(minCoins, subResult + 1);
if (minCoins == 1)
{
break;
}
}
}
}
return results[index] = minCoins == int.MaxValue ? -1 : minCoins;
}
}