LeetCode Combination Sum

本文介绍了一种算法,用于从给定的候选数集中找出所有可能的组合,使得这些组合的总和等于目标数。算法通过排序候选数、递归选择并检查组合总和是否达到目标数来实现。当找到符合条件的组合时,将其记录下来。该过程确保了不重复的组合,并且组合中的元素按非降序排列。

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

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

The same repeated number may be chosen from C unlimited number of times.

Note:

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

For example, given candidate set 2,3,6,7 and target 7
A solution set is: 
[7] 
[2, 2, 3] 


题意:给出一个集合和一个目标数,求可以构成目标数的所有子集
思路:属于组合问题,将数组从小到大排序,然后依次填入选择的数,如果当前计算的和大于目标数,就不继续。如果相等,将结果记录。如果小于,选择当前数,继续递归
代码如下:

class Solution
{
    private void __combination(int[] candidates, int start, int cursum, int target, List<Integer> arr, List<List<Integer>> ans)
    {
        if (cursum == target)
        {
            ArrayList<Integer> tmp = new ArrayList<Integer>();
            for (Integer a : arr)
            {
                tmp.add(a);
            }

            ans.add(tmp);
            return;
        }

        for (int i = start; i < candidates.length; i++)
        {
            if (cursum + candidates[i] > target) return;
            arr.add(candidates[i]);
            int len = arr.size();
            __combination(candidates, i, cursum + candidates[i], target, arr, ans);
            arr.remove(len - 1);
        }
    }

    public List<List<Integer>> combinationSum(int[] candidates, int target)
    {
        Arrays.sort(candidates);

        List<List<Integer>> ans = new ArrayList<List<Integer>>();
        List<Integer> arr = new ArrayList<Integer>();

        __combination(candidates, 0, 0, target, 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、付费专栏及课程。

余额充值