-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCoinChange1
51 lines (35 loc) · 1.56 KB
/
CoinChange1
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
// This can be used for getting the output in the form of coin used, number of coins
//But this is not efficient as the DP approach, but can be used if the output is specific as said above
//Time complesxity O (amount ^coins.Length)
public Dictionary<int,int> CoinChange1(int[] coins, int amount){
var q = new Queue< Tuple<int,int,Dictionary<int,int>>>();
q.Enqueue(new Tuple<int,int,Dictionary<int,int>>(amount,0, new Dictionary<int,int>()) );
int mincnt = amount+1;
var visited = new bool[amount+1];
while(q.Count>0){
var t = q.Dequeue();
var amt = t.Item1;
var cnt = t.Item2;
var dict = t.Item3;
if(amt ==0){
return dict;
}
if( !visited[amt]){
for(int i =0; i< coins.Length; i++){
if(coins[i] > amt){
continue;
}
var dict1 = dict.ToDictionary(x=>x.Key,x=>x.Value);
if(dict1.ContainsKey(coins[i])){
dict1[coins[i]]++;
}
else{
dict1.Add(coins[i],1);
}
q.Enqueue(new Tuple<int,int,Dictionary<int,int>>(amt - coins[i],cnt+1,dict1) );
}
}
visited[amt] = true;
}
return new Dictionary<int,int>();
}