leetcode 40组合总和 II

package com.example.lettcode.dailyexercises;

import java.util.*;

/**
 * @Class CombinationSum2
 * @Description 40组合总和II
 * 给定一个数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。
 * candidates 中的每个数字在每个组合中只能使用一次。
 * <p>
 * 说明:
 * 所有数字(包括目标数)都是正整数。
 * 解集不能包含重复的组合。
 * <p>
 * 示例 1:
 * 输入: candidates = [10,1,2,7,6,1,5], target = 8,
 * 所求解集为:
 * [
 * [1, 7],
 * [1, 2, 5],
 * [2, 6],
 * [1, 1, 6]
 * ]
 * <p>
 * 示例 2:
 * 输入: candidates = [2,5,2,1,2], target = 5,
 * 所求解集为:
 * [
 *   [1,2,2],
 *   [5]
 * ]
 * @Author
 * @Date 2020/9/9
 **/
public class CombinationSum2 {
    public static List<List<Integer>> combinationSum2(int[] candidates, int target) {
        Arrays.sort(candidates);
        if (candidates.length <= 0) {
            return new ArrayList<>();
        }
        Set<List<Integer>> res = new HashSet<>();
        List<Integer> integerList = new ArrayList<>();
        recur(res, integerList, candidates, target, 0);
        List<List<Integer>> resLists = new ArrayList<>();
        for (List<Integer> integers : res) {
            resLists.add(integers);
        }
        return resLists;
    }

    // 回溯
    public static void recur(Set<List<Integer>> res, List<Integer> integers, int[] candidates, int target, int idx) {
        // 判断找到的一组列表是否符合要求
        if (target == 0) {
            res.add(new ArrayList<>(integers));
            return;
        }
        if (idx >= candidates.length) {
            return;
        }
        // 包含当前位置的元素
        if (target - candidates[idx] >= 0) {
            integers.add(candidates[idx]);
            recur(res, integers, candidates, target - candidates[idx], idx + 1);
            integers.remove(integers.size() - 1);
        }
        // 跳过当前位置的元素
        recur(res, integers, candidates, target, idx + 1);
    }

    public static void main(String[] args) {
        int[] candidates = new int[]{10, 1, 2, 7, 6, 1, 5};
        int target = 8;
        List<List<Integer>> res = combinationSum2(candidates, target);
        System.out.println("CombinationSum2 demo01 result:");
        for (List<Integer> integerList : res) {
            for (Integer integer : integerList) {
                System.out.print("," + integer);
            }
            System.out.println();
        }

        candidates = new int[]{2, 5, 2, 1, 2};
        target = 5;
        res = combinationSum2(candidates, target);
        System.out.println("CombinationSum2 demo02 result:");
        for (List<Integer> integerList : res) {
            for (Integer integer : integerList) {
                System.out.print("," + integer);
            }
            System.out.println();
        }
    }
}
原文地址:https://www.cnblogs.com/fyusac/p/13653875.html