LeetCode Combination Sum II

本文详细解析了给定数组和目标数的情况下,寻找所有可能的组合以达成目标数的算法实现。通过递归方法,利用哈希映射记录每个元素出现次数,并确保组合唯一且非递减。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.

Each number in C may only be used once in the combination.

Note:

  • All numbers (including target) will be positive integers.
  • Elements in a combination (a1a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
  • The solution set must not contain duplicate combinations.

For example, given candidate set 10,1,2,7,6,1,5 and target 8
A solution set is: 
[1, 7] 
[1, 2, 5] 
[2, 6] 

[1, 1, 6] 

题意:给出一个数组(数组中可能有重复的数)和一个目标数,求其构成目标数的所有组合

思路:由于数组中有重复,需要有一个数组记录原数组中不同的数及相应的数在原来数组中出现的次数。在递归过程中,结束条件是当前记录的总数和等于目标数就退出。如果当前选择的数的计数非0,就选择该数,同时记录当前所选择的数的总和,继续递归。

代码如下:

class Solution
{
    private void __combinationSum2(int[] candidates, int start, int cursum, int total, Map<Integer, Integer> map, List<Integer> arr, List<List<Integer>> ans)
    {
        if (cursum == total)
        {
            List<Integer> tmp = new ArrayList<Integer>();
            tmp.addAll(arr);

            ans.add(tmp);
            return;
        }

       for (int i = start; i < candidates.length; i++)
       {
           int c = map.get(candidates[i]);
           if (c > 0)
           {
               if (cursum + candidates[i] > total) return;
               arr.add(candidates[i]);
               int len = arr.size();
               map.put(candidates[i], c - 1);
               __combinationSum2(candidates, i, cursum + candidates[i], total, map, arr, ans);
               arr.remove(len - 1);
               map.put(candidates[i], c);
           }
       }
    }

    public List<List<Integer>> combinationSum2(int[] candidates, int target)
    {
        Arrays.sort(candidates);
        List<Integer> arr = new ArrayList<Integer>();
        List<List<Integer>> ans = new ArrayList<List<Integer>>();

        Map<Integer, Integer> map = new TreeMap<Integer, Integer>();

        for (int num : candidates)
        {
            if (map.containsKey(num))
            {
                map.put(num, map.get(num) + 1);
            }
            else {
                map.put(num, 1);
            }
        }

        int[] cand = new int[map.size()];
        int c = 0;
        for (Integer k : map.keySet())
        {
            cand[c++] = k;
        }
        __combinationSum2(cand, 0, 0, target, map, arr, ans);
        return ans;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

kgduu

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值