题解 | #牛群分组II#

牛群分组II

https://www.nowcoder.com/practice/9ebc32fee9b54bfa9f9c3deca80febb0

知识点:回溯

思路:题意,和上一题类似,上一题是让我们选出,目标凑齐的数字,但是可以重复,这题不能重复,我们只需要用一个数组进行标记即可,

编程语言:java

import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param candidates int整型一维数组
     * @param target int整型
     * @return int整型二维数组
     */
    public int[][] cowCombinationSum2(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;
    }

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

        for (int i = start; i < candidates.length; i++) {
            if (i > start && candidates[i] == candidates[i - 1]) {
                continue; // 跳过重复的数字,避免重复组合
            }
            tempList.add(candidates[i]);
            backtrack(candidates, target - candidates[i], i + 1, tempList,
                      result); // 下一轮从 i+1 开始,避免重复选取同一个数字
            tempList.remove(tempList.size() - 1);
        }
    }
}

全部评论

相关推荐

king122:实习经历可以重点写这里这里写的清晰一点,分点写。技能特长一般是放在上面的,而且你的实习经历不能只写实现了一些简单的接口,你要去写一些难点和亮点。甚至可以写一些数字指标上去,只要你能配合业务讲出来,根据我说的这些自己简单包装一下,面试应该会更多,至于笔试和八股,那就只能纯靠自己了,对项目包装感兴趣可以找我
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
03-28 13:48
hory权:校招vip纯神人了,还说自己是什么师范大学的
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务