Skip to content

Instantly share code, notes, and snippets.

@ylegall
Created November 10, 2013 20:41
Show Gist options
  • Save ylegall/7403660 to your computer and use it in GitHub Desktop.
Save ylegall/7403660 to your computer and use it in GitHub Desktop.
Find smallest collection of coins with a given sum.
import java.util.*;
public class Coins
{
static List<Integer> makeChange(int[] coins, int sum) {
return makeChange(coins, new ArrayList<Integer>(), sum);
}
static List<Integer> makeChange(int[] coins, List<Integer> accum, int sum) {
if (sum == 0) {
return accum;
}
int minSize = Integer.MAX_VALUE;
List<Integer> result = null;
for (int c : coins) {
if (c > sum) continue;
accum.add(c);
List<Integer> tmp = makeChange(coins, new ArrayList<>(accum), sum - c);
accum.remove(accum.size()-1);
if (tmp != null && tmp.size() < minSize) {
minSize = tmp.size();
result = tmp;
}
}
return result;
}
public static void main(String[] args) {
System.out.println(makeChange(new int[] {13,4,3}, 18));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment