[LeetCode] #40 组合总和 II

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

candidates 中的每个数字在每个组合中只能使用一次。

注意:解集不能包含重复的组合。

输入: candidates = [10,1,2,7,6,1,5], target = 8,
输出:
[
[1,1,6],
[1,2,5],
[1,7],
[2,6]
]

[LeetCode] #39 组合总和思路相同,使用回溯算法

class Solution {
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        List<List<Integer>> res = new ArrayList<>();
        List<Integer> list = new ArrayList<>();
        Arrays.sort(candidates);
        helper(candidates, target, res, list, 0);
        return res;
    }
    private void helper(int[] candidates, int target, List<List<Integer>> res, List<Integer> list, int index) {
        if(target == 0) {
            res.add(new ArrayList<>(list));
            return;
        }
        for(int i = index; i < candidates.length; i++) {
            if(target - candidates[i] >= 0) {
                if(i > index && candidates[i]==candidates[i-1]) continue;
                list.add(candidates[i]);
                helper(candidates, target - candidates[i], res, list, i + 1);
                list.remove(list.size()-1);
            } else {
                break;
            }
        }
    }
}

知识点:

总结:

posted @ 2021-10-14 15:23  1243741754  阅读(17)  评论(0编辑  收藏  举报