非常经典的方式:
- DFS 枚举所有子集
- 存每个子集的副本(解决了引用问题)
- 最后遍历所有子集计算最大值
import java.util.*;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
static int max = 0;
static List<List<Integer>> res = new ArrayList<>();
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
//就是子集呗
int n = in.nextInt();
int m = in.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = in.nextInt();
}
dfs(a, 0, new ArrayList<>());
for (List<Integer> list : res) {
long sum = 0;
for (int num : list) sum += num;
int mod = (int)(sum % m);
max = Math.max(max, mod);
}
System.out.print(max);
}
public static void dfs( int[] a, int index, List<Integer> path) {
res.add(new ArrayList<>(path));
for (int i = index; i < a.length; i++) {
path.add(a[i]);
dfs(a, i + 1, path);
path.remove(path.size() - 1);
}
}
}
优化思路:直接在递归中更新最大值
总结教训
基本类型 vs 引用类型:
- 基本类型(int, long 等):传的是值,但如果在循环中修改,会影响后续
- 引用类型(List, 数组):传的是引用,需要手动回溯(add/remove 成对出现)
黄金法则:在递归循环中,如果要传“修改后的值”给下一层,直接用表达式传,不要修改当前层的变量。
import java.util.*;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
static int max = 0;
static int mod = 0;
static int m;
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
//就是子集呗
int n = in.nextInt();
m = in.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = in.nextInt();
}
dfs(a, 0, mod);
System.out.print(max);
}
public static void dfs( int[] a, int index,int mod) {
if(mod>max){
max = mod;
}
for (int i = index; i < a.length; i++) {
int newmod = (mod+a[i] )%m;
dfs(a, i + 1, newmod);
}
}
}

京公网安备 11010502036488号