39. 组合总和

题目链接

39. 组合总和 - 力扣(LeetCode)

题目描述

思路

1.因为不能返回的组合不能重复,因此,应该用index数组下标来便利,防止重复

2.对于某个数来说有两种选法:不选,选(可以多选)

代码

public class t1 {
    List<List<Integer>> res=new ArrayList<List<Integer>>();
    List<Integer> temp=new ArrayList<Integer>();
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        dfs(0,target,candidates);
        return res;
    }
    private void dfs(int index,int target,int[] candidates){
        if(index==candidates.length){
            //遍历完未满足,退出
            return;
        }
        if(target==0){
            //满足条件,添加到结果中
            res.add(new ArrayList<Integer>(temp));
            return;
        }
        //不选,跳过
        dfs(index+1,target,candidates);
        //提前剪枝
        if(target>=candidates[index]){
            //选,可以多选,所以index不变
            temp.add(candidates[index]);
            dfs(index,target-candidates[index],candidates);
            temp.remove(temp.size()-1);
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值