40. 组合总和 II

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

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

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/combination-sum-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

class Solution {

    private static void solve(List<Integer> nums, List<Integer> counts, List<List<Integer>> ret, LinkedList<Integer> path, int index, int target) {
        if (target == 0) {
            ret.add(new ArrayList<>(path));
            return;
        }

        if (index == nums.size() || target < nums.get(index)) {
            return;
        }


        solve(nums, counts, ret, path, index + 1, target);

        for (int i = 1; i <= counts.get(index) && target - i * nums.get(index) >= 0; ++i) {
            path.offerLast(nums.get(index));
            solve(nums, counts, ret, path, index + 1, target - i * nums.get(index));
        }

        for (int i = 1; i <= counts.get(index) && target - i * nums.get(index) >= 0; ++i) {
            path.pollLast();
        }
    }


    public static List<List<Integer>> combinationSum2(int[] candidates, int target) {
        if (candidates == null || candidates.length == 0) {
            return new ArrayList<>(0);
        }

        List<List<Integer>> ret = new ArrayList<>();

        Arrays.sort(candidates);


        int count = 1;

        ArrayList<Integer> nums = new ArrayList<>();
        ArrayList<Integer> counts = new ArrayList<>();

        for (int i = 1; i < candidates.length; ++i) {
            if (candidates[i] == candidates[i - 1]) {
                count++;
            } else {
                nums.add(candidates[i - 1]);
                counts.add(count);
                count = 1;
            }
        }

        nums.add(candidates[candidates.length - 1]);
        counts.add(count);

        solve(nums, counts, ret, new LinkedList<>(), 0, target);

        return ret;
    }
}
posted @ 2021-12-03 14:13  Tianyiya  阅读(30)  评论(0)    收藏  举报