50,686
社区成员
发帖
与我相关
我的任务
分享
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
public class Calculator {
private static final int[] UNITS = {100, 50, 20, 10, 5, 1};
private List<String> components = new LinkedList<String>();
private int target;
private Set<String> results = new TreeSet<String>();
public Calculator(int target) {
this.target = target;
}
public void calculate() {
doCalculate(target, 0, 0);
}
public Set<String> getResults() {
return results;
}
private void doCalculate(int target, int currentSum, int index) {
if (target == currentSum) {
results.add(components.toString());
return;
}
for (int s = index; s < UNITS.length; ++s) {
for (int i = 0; i <= (target - currentSum) / UNITS[s]; ++i) {
if (currentSum + UNITS[s] * i <= target) {
if (i != 0) {
components.add(UNITS[s] + " * " + i);
}
doCalculate(target, currentSum + UNITS[s] * i, s + 1);
if (i != 0) {
components.remove(components.size() - 1);
}
}
}
}
}
public static void main(String[] args) throws Exception {
Calculator calculator = new Calculator(36);
calculator.calculate();
calculator.getResults().stream().forEach(System.out::println);
}
}