华为OD机试 - 王者荣耀 - 回溯法(Java 2025 A卷 100分)

 

public class Main {
    private static int minDifference = Integer.MAX_VALUE; // 存储最小的差值

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int[] scores = Arrays.stream(sc.nextLine().split(" ")).mapToInt(Integer::parseInt).toArray();
        int totalSum = Arrays.stream(scores).sum();
        boolean[] visited = new boolean[scores.length];
        dfs(scores, visited, 0, scores.length, 5, totalSum);
        System.out.println(minDifference);
    }

    // 使用递归来枚举所有可能的5人组合
    private static void dfs(int[] scores, boolean[] visited, int start, int n, int k, int totalSum) {
        if (k == 0) {
            // 一旦选择了5人,计算这5人的评分总和
            int team1Sum = 0;
            for (int i = 0; i < n; i++) {
                if (visited[i]) {
                    team1Sum += scores[i];
                }
            }
            int team2Sum = totalSum - team1Sum;
            minDifference = Math.min(minDifference, Math.abs(team1Sum - team2Sum));
            return;
        }
        for (int i = start; i < n; i++) {
            visited[i] = true;
            dfs(scores, visited, i + 1, n, k - 1, totalSum);
            visited[i] = false; // 回溯
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值