题解 | #牛棚分组# java
牛棚分组
https://www.nowcoder.com/practice/d5740e4dde3740828491236c53737af4
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param n int整型
* @param k int整型
* @return int整型二维数组
*/
public int[][] combine (int n, int k) {
// write code here
List<List<Integer>> result = new ArrayList<>();
List<Integer> temp = new ArrayList<>();
dfs(1, n, k, temp, result);
// 将结果转换为二维数组
int[][] res = new int[result.size()][k];
for (int i = 0; i < result.size(); i++) {
for (int j = 0; j < k; j++) {
res[i][j] = result.get(i).get(j);
}
}
return res;
}
private void dfs(int start, int n, int k, List<Integer> temp,
List<List<Integer>> result) {
if (temp.size() == k) {
result.add(new ArrayList<>(temp));
return;
}
for (int i = start; i <= n; i++) {
temp.add(i);
dfs(i + 1, n, k, temp, result);
temp.remove(temp.size() - 1);
}
}
}
编程语言是Java。
该题考察的知识点是回溯算法。
定义一个递归函数,其中参数start表示当前选取的起始数字,n表示可选数字的范围,k表示要选取的数字个数,temp表示当前已选取的数字组合,result存储最终的结果。在每一层递归中,如果已选取的数字个数等于k,说明已经找到了满足条件的组合,将其加入到结果列表中。然后,在当前数字范围内遍历,将每个数字加入到临时组合中,然后递归调用下一层,继续选取下一个数字。递归结束后,需要将最后一个添加的数字从临时组合中移除,以便进行下一次选择。最后,将结果列表转换为二维数组并返回。

