题解 | #牛群喂食#

牛群喂食

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

import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param candidates int整型一维数组
     * @param target int整型
     * @return int整型二维数组
     */
    public static LinkedList<LinkedList<Integer>> linkedLists = new LinkedList<>();
    public int[][] cowCombinationSum (int[] candidates, int target) {
        // write code here
        Arrays.sort(candidates);
        search(candidates, target, 0, new LinkedList<>());
        int[][] arr = new int[linkedLists.size()][];
        for (int i = 0; i < linkedLists.size(); i++) {
            arr[i] = new int[linkedLists.get(i).size()];
            for (int j = 0; j < linkedLists.get(i).size(); j++) {
                arr[i][j] = linkedLists.get(i).get(j);
            }
        }
        return arr;
    }

    public void search(int[] candidates, int target, int cur,
                       LinkedList<Integer> linkedList) {
        if (cur == target) {
            linkedLists.add(new LinkedList<>(linkedList));
            return;
        }
        if (cur > target) {
            return;
        }
        for (int i = 0; i < candidates.length; i++) {
            if(linkedList.size()>0 && candidates[i]<linkedList.get(linkedList.size()-1)){
                continue;
            }
            linkedList.add(candidates[i]);
            search(candidates, target, cur + candidates[i], linkedList);
            linkedList.remove(linkedList.size() - 1);
        }
    }
}

本题可以选择用递归方法来完成题目要求,所用编程语言是java。

递归方法就考虑N叉树的建立,对于路径值之和大于目标值的话停止继续往下遍历,对于路径值之和等于目标值的话也停止往下遍历,并将此路径加入到集合当中。对于重复组合的问题,我们需要剪枝,比如 1,1,1,3组合和1,3,1,1组合是同一组合,但是我们只能将其第一个加入集合中,

if(linkedList.size()>0 && candidates[i]<linkedList.get(linkedList.size()-1)){

continue;

}这段代码就是剪枝防止组合重复

全部评论

相关推荐

迷茫的大四🐶:都收获五个了,兄弟那还说啥,不用改了,去玩吧
点赞 评论 收藏
分享
09-24 18:30
已编辑
长春工业大学 产品经理
小肥罗:HR就是好人的缩写哈哈哈哈
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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