从n个数中选择m个数
题目描述
- 给定两个整数 n 和 m,长度为n的数组 中所有可能的 m 个数的组合。你可以按 任何顺序 返回答案。
- 递归实现组合型枚举
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class MxuanN {
private static List<List<Integer>> res = new ArrayList<>();
private static List<Integer> temp = new ArrayList<>();
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt(), m = sc.nextInt();
int[] nums = new int[n];
for (int i = 0; i < n; i++) {
nums[i] = sc.nextInt();
}
Arrays.sort(nums);
/*for (int i = 0; i < n; i++) {
res = process(nums, n, i + 1);
}*/
res = process(nums, n, m);
System.out.println(res);
}
private static List<List<Integer>> process(int[] nums, int n, int m) {
dfs(nums, n, m, 0);
return res;
}
private static void dfs(int[] nums, int n, int m, int cur) {
if (temp.size() + (n - cur) < m){
return;
}
if (temp.size() == m){
res.add(new ArrayList<>(temp));
return;
}
// 要
temp.add(nums[cur]);
dfs(nums, n, m, cur + 1);
temp.remove(temp.size() - 1);
// 不要
dfs(nums, n, m, cur + 1);
}
}
- 测试

这篇博客探讨了如何使用递归方法在给定的整数数组中生成所有可能的m个数的组合。通过一个Java程序,作者展示了如何利用深度优先搜索(DFS)策略来解决这个问题。程序首先读取n和m的值,然后对数组进行排序,接着调用递归过程生成组合,并将结果存储在一个列表中。最后,程序打印出所有的组合结果。

3万+

被折叠的 条评论
为什么被折叠?



