for循环嵌套递归函数的运行-跳房子II

例题

来源:华为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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值