使用java写一段代码,要求:在m个数里面取n个数,要求列出所有组合
时间: 2024-02-03 19:14:59 浏览: 30
以下是使用递归方法实现的Java代码:
```java
import java.util.ArrayList;
import java.util.List;
public class Combination {
public static void main(String[] args) {
int[] nums = {1, 2, 3, 4};
int n = 3;
List<List<Integer>> result = combine(nums, n);
for (List<Integer> list : result) {
System.out.println(list);
}
}
public static List<List<Integer>> combine(int[] nums, int n) {
List<List<Integer>> result = new ArrayList<>();
if (nums == null || nums.length == 0 || n == 0 || nums.length < n) {
return result;
}
List<Integer> temp = new ArrayList<>();
dfs(nums, n, 0, temp, result);
return result;
}
private static void dfs(int[] nums, int n, int start, List<Integer> temp, List<List<Integer>> result) {
if (temp.size() == n) {
result.add(new ArrayList<>(temp));
return;
}
for (int i = start; i < nums.length; i++) {
temp.add(nums[i]);
dfs(nums, n, i + 1, temp, result);
temp.remove(temp.size() - 1);
}
}
}
```
其中,`combine`方法接受一个整型数组`nums`和一个整数`n`,返回一个包含所有组合的列表。`dfs`方法是递归函数,用于实现深度优先搜索。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)