题解 | #牛群喂食# java
牛群喂食
https://www.nowcoder.com/practice/591c222d73914c1ba031a660db2ef73f
import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param candidates int整型一维数组 * @param target int整型 * @return int整型二维数组 */ public int[][] cowCombinationSum (int[] candidates, int target) { // write code here Arrays.sort(candidates); List<List<Integer>> result = new ArrayList<>(); List<Integer> combination = new ArrayList<>(); dfs(candidates, target, result, combination, 0); int[][] ans = new int[result.size()][]; for (int i = 0; i < result.size(); i++) { ans[i] = new int[result.get(i).size()]; for (int j = 0; j < result.get(i).size(); j++) { ans[i][j] = result.get(i).get(j); } } return ans; } private void dfs(int[] candidates, int target, List<List<Integer>> result, List<Integer> combination, int begin) { if (target == 0) { result.add(new ArrayList<>(combination)); return; } for (int i = begin; i < candidates.length && target >= candidates[i]; i++) { combination.add(candidates[i]); dfs(candidates, target - candidates[i], result, combination, i); combination.remove(combination.size() - 1); } } }
编程语言是Java。
该题考察的知识点是回溯算法,通过递归和回溯的方式找到给定数组中所有的组合,使其和等于目标数。
代码简短的文字解释如下:
- 创建一个空的列表 result 用于存储最终的结果。
- 创建一个空的列表 combination 用于存储当前的组合。
- 调用 dfs 方法进行回溯,传入排序后的数组 candidates、目标数 target、结果列表 result、当前组合列表 combination,以及起始位置 begin。
- 在 dfs 方法中,首先判断如果目标数 target 等于 0,说明当前组合的数字之和等于目标数,将此组合加入结果列表中,然后返回。
- 遍历数组 candidates,从指定的起始位置 begin 开始循环。
- 如果当前数字大于目标数 target,则直接跳过。
- 将当前数字添加到组合列表 combination 中。
- 递归调用 dfs 方法,将目标数更新为 target 减去当前数字,继续在剩余的数组中查找下一个数字的组合。
- 每次递归返回后,将组合列表 combination 的最后一个数字移除,以便尝试下一个数字的组合。
- 最后将结果列表 result 转换为二维数组并返回。