华为机试练习:分月饼

本文介绍了如何使用Java编写一个名为`findSumCombinations`的方法,通过回溯算法解决给定整数n和m,找到所有和为m且相邻元素差不超过3的整数子数组的组合问题。程序还包含了输入处理和结果过滤部分。
摘要由CSDN通过智能技术生成

在这里插入图片描述在这里插入图片描述
在这里插入图片描述在这里插入图片描述

参考代码:

package com.cfl;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Test {

    public static List<List<Integer>> findSumCombinations(int n, int m) {
        List<List<Integer>> result = new ArrayList<>();
        backtrack(result, new ArrayList<>(), n, m, 0, 0);
        return result;
    }

    private static void backtrack(List<List<Integer>> result, List<Integer> currentList, int n, int m, int start, int sum) {
        if (currentList.size() == n && sum == m) {
            result.add(new ArrayList<>(currentList));
            return;
        }

        if (currentList.size() < n) {
            for (int i = start; i <= m - (n - currentList.size()) * start; i++) {
                currentList.add(i);
                backtrack(result, currentList, n, m, i, sum + i);
                currentList.remove(currentList.size() - 1); // 回溯,移除当前尝试的数
            }
        }
    }

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        String str = input.nextLine();
        String[] split = str.split(" ");
        int n = Integer.parseInt(split[0]);
        int m = Integer.parseInt(split[1]);
        List<List<Integer>> combinations = findSumCombinations(n, m);
        combinations.removeIf(combination -> combination.get(0) == 0);
        List<List<Integer>> temp = new ArrayList<>();
        for (List<Integer> combination : combinations) {
            for (int i = 0; i < combination.size(); i++) {
                if(i==combination.size()-1){
                    break;
                }
                if(combination.get(i+1)-combination.get(i)>3){
                    //System.out.println(combination);
                    temp.add(combination);
                }
            }
        }
        //System.out.println("---------------------------------");
        for (int i = 0; i < combinations.size(); i++) {
            for (int j = 0; j < temp.size(); j++) {
                if(combinations.get(i) == temp.get(j)){
                    combinations.remove(i);
                }
            }
        }
//        for (List<Integer> combination : combinations) {
//            System.out.println(combination);
//        }
        System.out.println(combinations.size());
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值