39. Combination Sum

本文介绍了一种解决组合求和问题的Backtrack算法实现,通过排序数组来优化搜索过程,减少不必要的遍历,提高效率。

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

Backtrack的典型,为了更好的back,给原数组SORT一下会比较好,加一个数超过TARGET可以直接剪枝了。

public class Solution {
    public List<List<Integer>> combinationSum(int[] nums, int target) 
    {
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        if(nums.length == 0) return res;

        Arrays.sort(nums);
        helper(res,nums,new ArrayList<Integer>(),target,0);
        
        return res;
    }
    
    public void helper(List<List<Integer>> res, int[] nums, List<Integer> tempList, int target, int m)
    {
        if(target == 0) res.add(tempList);
        
        else if(target < 0) return;
        else
        {
            for(int i = m; i < nums.length; i++)
            {
                if(target - nums[i] < 0) break;
                tempList.add(nums[i]);
                helper(res,nums,new ArrayList<Integer>(tempList),target - nums[i],i);
                tempList.remove(tempList.size()-1);
            }
        }
    }
}

-----

三刷。

基本一回事,排序一下可以提前剪枝,既然没有负数。有负数就不能一个数无限次的用了。。

Time: O(n^k) n是多少个元素,K是target。这个题不会算,感觉还是指数级别,但是实际上跟具体数据有关,target(k)不停地减少,能用的元素也原来越少,总之不会算。。。
Space: O(n)

public class Solution {
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        if (candidates.length == 0) return res;
        Arrays.sort(candidates);
        dfs(res, candidates, target, 0, new ArrayList<>());
        return res;
    }
    public void dfs(List<List<Integer>> res, int[] nums, int target, int m, List<Integer> tempList) {
        if (target == 0) {
            res.add(tempList);
            return;
        } else {
            for (int i = m; i < nums.length; i++) {
                if (target - nums[i] < 0) break;
                if (i != m && nums[i] == nums[i-1]) continue;
                tempList.add(nums[i]);
                dfs(res, nums, target - nums[i], i, new ArrayList<>(tempList));
                tempList.remove(tempList.size() - 1);
                
            }
            return;
        }
    }
}

转载于:https://www.cnblogs.com/reboot329/articles/6041348.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值