题解 | #牛群喂食#

牛群喂食

https://www.nowcoder.com/practice/591c222d73914c1ba031a660db2ef73f

知识点:回溯

思路:使用回溯实现全排列,因为这次比上一次,不需要在标记used,使用的元素,因此直接遍历即可,后续回溯一一标记判断,

如果累加的值等于我们想要的target,目标值,那么我们就存储到一个集合中

编程语言:java

import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param candidates int整型一维数组
     * @param target int整型
     * @return int整型二维数组
     */
    public int[][] cowCombinationSum(int[] candidates, int target) {
        List<List<Integer>> result = new ArrayList<>();
        Arrays.sort(candidates);
        backtrack(candidates, target, 0, new ArrayList<>(), result);

        int[][] ans = new int[result.size()][];
        for (int i = 0; i < result.size(); i++) {
            ans[i] = result.get(i).stream().mapToInt(Integer::intValue).toArray();
        }

        return ans;
    }

    private void backtrack(int[] candidates, int target, int start,
                           List<Integer> tempList, List<List<Integer>> result) {
        //终止条件
        if (target < 0) {
            return;
        }
        if (target == 0) {
            result.add(new ArrayList<>(tempList));
            return;
        }

        for (int i = start; i < candidates.length; i++) {
            tempList.add(candidates[i]);
            backtrack(candidates, target - candidates[i], i, tempList, result);
            tempList.remove(tempList.size() - 1);
        }
    }
}

全部评论

相关推荐

不愿透露姓名的神秘牛友
2025-11-21 11:29
已编辑
斯卡蒂味的鱼汤:知道你不会来数马,就不捞你😂最近数马疯狂扩招,招聘要求挺低的,你能力肯定够,应该就是因为太强了,知道你不会来才不捞你
投递腾讯云智研发等公司8个岗位
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务