组合总和-Java-LeetCode第39题

该文章介绍了一个使用Java实现的算法,通过深度优先搜索(DFS)方法来找到无重复元素的整数数组中所有和为目标数的不同组合。在DFS过程中,如果当前数字满足条件,就将其加入临时数组并递归搜索,当目标数为0时,将临时数组添加到结果中。由于每个数字可以无限重复使用,所以不需在递归后增加数组索引。文章确保了结果组合的数量少于150个。
摘要由CSDN通过智能技术生成

 

给你一个 无重复元素 的整数数组 candidates 和一个目标整数 target ,找出 candidates 中可以使数字和为目标数 target 的 所有 不同组合 ,并以列表形式返回。你可以按 任意顺序 返回这些组合。

candidates 中的 同一个 数字可以 无限制重复被选取 。如果至少一个数字的被选数量不同,则两种组合是不同的。 

对于给定的输入,保证和为 target 的不同组合数少于 150 个。

class Solution {
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> ans=new ArrayList<List<Integer>>();
        List<Integer> temp=new ArrayList<Integer>();
        dfs(candidates,target,ans,temp,0);
        return ans;
    }

    public void dfs(int[] candidates,int target,List<List<Integer>> ans,List<Integer> temp,int num){
        if(num==candidates.length){
            return;
        }
        if(target==0){
            ans.add(new ArrayList<Integer>(temp));
            return;
        }
        dfs(candidates,target,ans,temp,num+1);
        if(target-candidates[num]>=0){
            temp.add(candidates[num]);
            dfs(candidates,target-candidates[num],ans,temp,num);
            temp.remove(temp.size()-1);
        }
    }
}

思路:回溯法。

先建立一个二重数组用来保存最终的结果组合,再建立一个数组用来临时保存符合条件的数组。

然后进入dfs函数进行运算。

如果当前数a符合target-a>=0,则将该数添加到临时数组中,target-a继续进入下一次dfs。(注意:因为每个数可以无限重复使用,因此num不需要+1)

如果target==0,说明当前临时数组里的数符合条件,将该临时数组加入到二重数组中。

剪枝函数是当前数组的数已被用完。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值