0039_Combination Sum

本文介绍了一种解决LeetCode上组合总和问题的方法,采用递归算法找到所有可能的数字组合,使得这些数字之和等于给定的目标值。通过实例演示了如何避免重复解并确保解集的唯一性。

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

Given a set of candidate numbers (C) (without duplicates) 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.
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]
]

JAVA

方法一

  刚开始想使用hashmap来做,但是发现题中要求组合唯一,这样一来用hashmap出来的结果一定会有重复的,那么就要进行去重操作,而我又不会做。。
  所以使用递归的方式,注意边界条件以及第一次调用时需要使用循环,以便可以从任意一个下标作为起始位置,否则会丢解。本来只是用这种暴力方式来试试,没想到效率在前1/4。莫非在LeetCode中递归的效率特别高???

public class Solution {
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> result = new LinkedList<List<Integer>>();
        LinkedList<Integer> tempResult = new LinkedList<Integer>();
        if(candidates.length != 0){
            Arrays.sort(candidates);
            for (int i = 0; i < candidates.length; i++) {
                getResult(candidates,target,result,i,0,tempResult);
            }
        }
        return result;
    }
    public void getResult(int[] candidates, int target,List<List<Integer>> result,
                          int currentIndex,int currentSum,LinkedList<Integer> tempResult){
        currentSum += candidates[currentIndex];
        tempResult.add(candidates[currentIndex]);
        if(currentSum == target){
            result.add((LinkedList)tempResult.clone());
        }
        while(currentIndex < candidates.length && currentSum + candidates[currentIndex] <= target){
            getResult(candidates,target,result,currentIndex,currentSum,tempResult);
            ++currentIndex;
        }
        tempResult.removeLast();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值