题解 | #牛群喂食#

牛群喂食

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

知识点:回溯

题目要求找到数组中和为target的序列,并且序列中的元素可以重复,原数组的元素并没有重复元素,这就确保了只有在同一个位置才可以找到该元素,题目还要求需要将最终结果升序排列,我们可以先对原数组进行升序排序,然后依次遍历自身及其后续元素,累加得到的元素和,当元素和等于target时,保存当前遍历的所有元素,当超过target时需要停止后续遍历。

Java题解如下

import java.util.*;


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

    public int[][] cowCombinationSum (int[] candidates, int target) {
        // write code here
        Arrays.sort(candidates);
        this.candidates = candidates;
        this.target = target;
        for(int i = 0; i < candidates.length; i++) {
            dfs(new ArrayList<>(), i, 0);
        }
        int[][] ans = new int[res.size()][];
        for(int i = 0; i < res.size(); i++) {
            ans[i] = new int[res.get(i).size()];
            for(int j = 0; j < res.get(i).size(); j++) {
                ans[i][j] = res.get(i).get(j);
            }
        }
        return ans;
    }

    private void dfs(List<Integer> list, int index, int sum) {
        if(sum + candidates[index] > target) {
            return;
        }
        sum += candidates[index];
        list.add(candidates[index]);
        if(sum == target) {
            res.add(new ArrayList<>(list));
        }
        for(int i = index; i < candidates.length; i++) {
            dfs(list, i, sum);
        }
        sum -= candidates[index];
        list.remove(list.size() - 1);
    }
}

全部评论

相关推荐

03-26 13:04
已编辑
电子科技大学 算法工程师
xiaowl:你这个简历“条目上”都比较有深度性,但是实际上面试官又没法很好的评估你是怎么达到很多看上去很厉害的结果的。要避免一些看上去很厉害的包装,比如高效的内存复用策略的表达,如果仅是简单的一些内存共享机制,而且面试上也没有深挖的空间,就不要这样表达。比如,工程化模式本质上可能就是定义了一些abstract class,那也就没特别多值得讲的内容。建议简历上应该侧重那些你花了大量时间和精力解决、研究的问题,不要过分追求“丰富”,而是关注在技术深入度、问题解决能力的表现上。
没有实习经历,还有机会进...
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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