从n个数中选取m个数的所有组合Java实现代码
时间: 2023-10-25 09:09:56 浏览: 53
以下是从n个数中选取m个数的所有组合的Java实现代码:
```
public static List<List<Integer>> combinations(int[] nums, int m) {
List<List<Integer>> result = new ArrayList<>();
backtrack(result, new ArrayList<>(), nums, m, 0);
return result;
}
private static void backtrack(List<List<Integer>> result, List<Integer> tempList, int[] nums, int m, int start) {
if (tempList.size() == m) {
result.add(new ArrayList<>(tempList));
} else {
for (int i = start; i < nums.length; i++) {
tempList.add(nums[i]);
backtrack(result, tempList, nums, m, i + 1);
tempList.remove(tempList.size() - 1);
}
}
}
```
其中,`nums`是给定的整数数组,`m`是需要选取的数的个数。该函数返回一个列表,其中每个元素是一个列表,表示一个组合。例如,`combinations(new int[]{1, 2, 3, 4}, 2)` 将返回`[[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]]`。