Представьте себе дерево, в котором каждый узел имеет значение и имеет 3 дочерних элементов, значение которых уменьшено соответственно на 7, 5 и 1
Таким образом, у узла с общим числом 15 будут дочерние элементы со значениями 8, 10, 14
Мы можем начать с первого узла, имеющего ваш итог, и рассчитать каждый уровень и остановиться, когда мы найдем дочернего элемента, равного 0. Мы также прекращаем смотреть на дочернего элемента, если его значение меньше 0.
Например, для 10:
10
/ | \
3 5 9
/ | \ / | \ / | \
-4 -2 2 -2 0 4 2 4 1
Мы находим ноль на глубине 2
private static int calculate(int total, int depth) {
if (total == 0)
return depth;
else {
int i = total - 7 >= 0 ? calculate(total - 7, depth+1) : Integer.MAX_VALUE;
int j = total - 5 >= 0 ? calculate(total - 5, depth+1) : Integer.MAX_VALUE;
int k = total - 1 >= 0 ? calculate(total - 1, depth+1) : Integer.MAX_VALUE;
return Collections.min(Arrays.asList(i, j, k));
}
}
This
int n = 10;
System.out.println("The number "+n+ " - " + calculate(n, 0) + " minimum options to create");
n = 7;
System.out.println("The number "+n+ " - " + calculate(n, 0) + " minimum options to create");
n = 6;
System.out.println("The number "+n+ " - " + calculate(n, 0) + " minimum options to create");
n = 18;
System.out.println("The number "+n+ " - " + calculate(n, 0) + " minimum options to create");
Выводит это
The number 10 - 2 minimum options to create
The number 7 - 1 minimum options to create
The number 6 - 2 minimum options to create
The number 18 - 4 minimum options to create
РЕДАКТИРОВАТЬ: То же самое в стиле фанк лямбда:
private static int calculate(int total, int depth) {
return total == 0 ?
depth :
Stream.of(7, 5, 1)
.map(i -> total - i >= 0 ? calculate(total - i, depth+1) : Integer.MAX_VALUE)
.min(Integer::compare)
.get();
}