题目
作为篮球队教练,你需要从以下名单中选出1号位至5号位各一名球员, 组成球队的首发阵容。
每位球员担任1号位至5号位时的评分如下表所示。请你计算首发阵容1 号位至5号位的评分之和最大可能是多少?
思路:照着上面的20行6列,创建一个数组,通过scanner类将数据输入。通过dfs回溯查找最大值。
详情看代码
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// 创建一个20行6列的数组
int[][] score = new int[20][6];
// 输入
for (int i = 0; i < score.length; i++) {
for (int j = 0; j < score[i].length; j++) {
score[i][j] = input.nextInt();
}
}
// 回溯查找最大值
dfs(score, 1, 0, new HashSet<>());
System.out.println(max);
}
// 找最大值
static int max = 0;
public static void dfs(int[][] score, int index, int tempSum, HashSet<Integer> set) {
// index 代表多少号位,1就是1号位,2就是2号位
// tempSum是求每种方案的值
// set用于判重:如果有一位球员在多种号位的值都很大,那么就要进行取舍
if (index == 6) {
// 若是6,表示人员已满
max = Math.max(tempSum, max);// 求所有方案中的最大值
return;
}
for (int i = 0; i < score.length; i++) {
// 从第1个人开始
if (!set.contains(i)) {
// 包含该球员就找下一个
set.add(i);
dfs(score, index + 1, tempSum + score[i][index], set);
set.remove(i);
}
}
}
答案:490
做题总结
这道题可以直接去找,不用编写代码,就是一个求最大值问题,细心一点,是可以做出来的。
但是如果编成代码的话,就需要思考怎么回溯能够将所有的情况遍历一遍,并且没有重复的球员。
end.