【LeetCode】39.Combination Sum(Medium)解题报告

本文详细解析了LeetCode第39题“组合总和”的解决方案,该题要求从给定候选数字集合中找到所有可能的组合,使这些组合的数字之和等于目标值。文章提供了使用深度优先搜索实现的具体代码示例。

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

【LeetCode】39.Combination Sum(Medium)解题报告

题目地址:https://leetcode.com/problems/combination-sum/description/
题目描述:

  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]]

  理解:连续四道题放到一起,每道题都有一点条件上的变化。这道题要求数字可以多次利用,不要求数字的个数。combo(res,candidates,target-candidates[i],tempList,i);这一行很重要,而且此类dfs很多模板题,要熟练。最后面if条件去重(结果中的重复list)。

Solution:

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

    }
}

Date:2017年12月12日

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值