美文网首页
leetcode题目40. 组合总和 II(java)

leetcode题目40. 组合总和 II(java)

作者: castlet | 来源:发表于2020-07-25 13:42 被阅读0次

题目描述

给定一个数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。candidates 中的 每个数字在每个组合中只能使用一次。所有数字(包括目标数)都是正整数。解集不能包含重复的组合

示例

输入: candidates = [10,1,2,7,6,1,5], target = 8,
所求解集为:
     [
     [1, 7],
     [1, 2, 5],
     [2, 6],
     [1, 1, 6]
     ]

代码

public List<List<Integer>> combinationSum_II(int[] candidates, int target) {

    List<List<Integer>> result = new ArrayList<>();
    LinkedList<Integer> path = new LinkedList<>();
    Arrays.sort(candidates); // 排序
    dfs_II(candidates, target, result, path, 0);
    return result;
}

public void dfs_II(int[] candidates, int target, List<List<Integer>> result, LinkedList<Integer> path, int begin) {
    if (target == 0) {
        // 找到了一条路径,将路径拷贝一份儿放到结果数组里
        result.add(new ArrayList<Integer>(path));
        return;
    }
    for (int i = begin; i < candidates.length; i ++) {
        if (candidates[i] > target) {
            // 剪枝,去除没必要的搜索
            return;
        }

        if (i > begin && candidates[i] == candidates[i - 1]) {
            // 剪枝,因为不允许重复,所以如果当前的值已经计算过了,就不再处理了
            continue;
        }

        path.add(candidates[i]);
        dfs_II(candidates, target - candidates[i], result, path, i + 1); // 递归
        path.removeLast(); // 每次回溯将最后一次加入的元素删除
    }
}

相关文章

  • 40. 组合总和 II

    40. 组合总和 II(难度:中等) 题目链接:https://leetcode-cn.com/problems/...

  • leetcode题目40. 组合总和 II(java)

    题目描述 给定一个数组 candidates 和一个目标数 target ,找出 candidates 中所有可以...

  • 40. 组合总和 II

    题目 40. 组合总和 II 给定一个数组 candidates 和一个目标数 target ,找出 candid...

  • leetcode 40. 组合总和 II(Java版)

    题目描述(题目难度,中等) 给定一个数组 candidates 和一个目标数 target ,找出 candida...

  • 数组相同数字聚集

    题目描述: 昨天做 leetcode 组合总和 II 这个题目时,碰到这样一个需求:给定一个数组,数组中存在相同的...

  • 40. 组合总和 II

    给定一个数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为...

  • 40.组合总和II

    题目给定一个数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字...

  • 40.组合总和 II

    自己解法 标准的回溯加剪枝,思路很清晰,但是在细节上出了点小问题,一个是递归的时候应该用i+1,用成了start ...

  • 40. 组合总和 II

    题目描述 给定一个数组 candidates 和一个目标数 target ,找出 candidates 中所有可以...

  • LeetCode 力扣 40. 组合总和 II

    题目描述(中等难度) 和上一道题非常像了,区别在于这里给的数组中有重复的数字,每个数字只能使用一次,然后同样是给出...

网友评论

      本文标题:leetcode题目40. 组合总和 II(java)

      本文链接:https://www.haomeiwen.com/subject/zjnplktx.html