例题
来源:华为OD机试题
跳房子II
跳房子,也叫跳飞机,是一种世界性的儿童游戏。
游戏参与者需要分多个回合按顺序跳到第1格直到房子的最后一格,然后获得一次选房子的机会,直到所有房子被选完,房子最多的人获胜。
跳房子的过程中,如果有踩线等违规行为,会结束当前回合,甚至可能倒退几步。假设房子的总格数是count,小红每回合可能连续跳的步数都放在数组steps中,请问数组中是否有一种步数的组合,可以让小红三个回合跳到最后一格?
如果有,请输出索引和最小的步数组合(数据保证索引和最小的步数组合是唯一的)。
注意:数组中的步数可以重复,但数组中的元素不能重复使用。
// 最小索引和
private static int min = Integer.MAX_VALUE;
// 三个回合跳到最后一格
private static final int three = 3;
// 房子总格数count
private static int count;
// 选出索引和最小的那一组数据
private static List<Integer> minIndexList;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// 房子总格数count
count = sc.nextInt();
sc.nextLine();
// 读取换行符
int[] steps = Arrays.stream(sc.nextLine().split(","))
.mapToInt(Integer::parseInt)
.toArray();
minIndexList = new ArrayList<>();
getMinSteps(steps, new ArrayList<>(), 0, 0);
System.out.println(minIndexList);
}
/**
* 选出索引和最小的那一组数据
*
* @param steps 每回合可能连续跳过的步数数组
* @param currentSteps 当前已跳的步数集合
* @param currentIndex 当前步数索引和
* @param sum 当前步数总和
*/
public static void getMinSteps(int[] steps, List<Integer> currentSteps, int currentIndex, int sum) {
System.out.println(currentSteps);
if (currentSteps.size() == three) {
if (sum == count && currentIndex < min) {
System.out.println("符合要求的小红跳的步数集合:"+currentSteps);
System.out.println("下角标之和:"+currentIndex);
min = currentIndex;
minIndexList = new ArrayList<>(currentSteps);
}
return;
}
for (int i = 0; i < steps.length; i++) {
// 尝试添加步数
currentSteps.add(steps[i]);
// 递归调用
getMinSteps(steps, currentSteps, currentIndex + i, sum + steps[i]);
// 回溯,移除最后一个步数
currentSteps.remove(currentSteps.size() - 1);
}
}
代码执行过程:
递归函数ge