题解 | #牛群喂食#
牛群喂食
https://www.nowcoder.com/practice/591c222d73914c1ba031a660db2ef73f?tpId=354&tqId=10594712&ru=/exam/oj&qru=/ta/interview-202-top/question-ranking&sourceUrl=%2Fexam%2Foj%3Fpage%3D1%26tab%3D%25E7%25AE%2597%25E6%25B3%2595%25E7%25AF%2587%26topicId%3D354
import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param candidates int整型一维数组 * @param target int整型 * @return int整型二维数组 */ public int[][] cowCombinationSum (int[] candidates, int target) { // write code here List<List<Integer>> result = new ArrayList<>(); Arrays.sort(candidates); // Sort the candidates in ascending order backtrack(result, new ArrayList<>(), candidates, target, 0); int[][] array = new int[result.size()][]; for (int i = 0; i < result.size(); i++) { List<Integer> sublist = result.get(i); array[i] = new int[sublist.size()]; for (int j = 0; j < sublist.size(); j++) { array[i][j] = sublist.get(j); } } return array; } private void backtrack(List<List<Integer>> result, List<Integer> current, int[] candidates, int target, int start) { if (target < 0) { return; // If target becomes negative, stop exploration } if (target == 0) { result.add(new ArrayList<>(current)); // Found a valid combination return; } for (int i = start; i < candidates.length; i++) { current.add(candidates[i]); // Note that we allow reusing the same candidate to generate combinations backtrack(result, current, candidates, target - candidates[i], i); current.remove(current.size() - 1); } } }
知识点:
递归
回溯
解题思路:
使用回溯算法来生成所有可能的食物组合,使其总量和为目标数 target。我们首先对 candidates 数组进行了升序排序,然后在 backtrack 方法中,我们尝试将每个 candidate 添加到当前组合中,递归地继续生成下一个食物组合。每次递归时,我们更新目标数为 target - candidates[i],以维护正确的剩余食物需求。