Java题解 | #牛群喂食#
牛群喂食
https://www.nowcoder.com/practice/591c222d73914c1ba031a660db2ef73f
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param candidates int整型一维数组
* @param target int整型
* @return int整型二维数组
*/
List<List<Integer>> ans = new ArrayList<>();
List<Integer> path = new ArrayList<>();
public int[][] cowCombinationSum(int[] candidates, int target) {
dfs(candidates, 0, target);
return convertTo2DArray(ans);
}
private void dfs(int[] candidates, int index, int target) {
if (target < 0) {
return;
}
if (target == 0) {
ans.add(new ArrayList<>(path));
return;
}
for (int i = index; i < candidates.length; i++) {
path.add(candidates[i]);
target -= candidates[i];
dfs(candidates, i, target);
path.remove(path.size() - 1);
target += candidates[i];
}
}
private int[][] convertTo2DArray(List<List<Integer>> list) {
int size = list.size();
int[][] result = new int[size][];
for (int i = 0; i < size; i++) {
List<Integer> row = list.get(i);
int rowSize = row.size();
result[i] = new int[rowSize];
for (int j = 0; j < rowSize; j++) {
result[i][j] = row.get(j);
}
}
return result;
}
}
编程语言是Java。
该题考察的知识点是回溯算法,用于在给定的数组中找到所有组合使得它们的和等于目标值。
使用回溯算法(DFS)来搜索所有可能的组合。类中定义了两个成员变量ans和path,分别用于存储所有符合条件的组合和暂时存储当前正在搜索的组合。在cowCombinationSum方法中,调用dfs方法进行深度搜索,从指定的index开始遍历candidates数组,并尝试加入当前元素到组合中。如果组合的和小于target,则继续深度搜索,否则回溯到上一步。当组合的和等于target时,将该组合添加到ans中。
将ans返回作为结果。
查看10道真题和解析