135题 Combination Sum

该博客介绍了一种解决组合总和问题的方法,即给定一组候选数字和一个目标数字,找出所有可能的不重复组合,使得候选数字的和等于目标数字。文章通过一个名为`Solution`的类实现,主要包含`combinationSum`和`helper`两个方法。`combinationSum`方法首先对输入的候选数字进行排序,并初始化结果列表和子集。`helper`方法采用回溯法递归地搜索所有可能的组合。当剩余目标为0时,将当前子集添加到结果中。整个过程确保了数字的非降序排列和结果的唯一性。

Combination Sum

Description
Given a set of candidate numbers candidates and a target number target. Find all unique combinations in candidates where the numbers sums to target.

The same repeated number may be chosen from candidates unlimited number of times.

All numbers (including target) will be positive integers.
Numbers in a combination a1, a2, … , ak must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak)
Different combinations can be in any order.
The solution set must not contain duplicate combinations.

public class Solution {
    /**
     * @param candidates: A list of integers
     * @param target: An integer
     * @return: A list of lists of integers
     */
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        // write your code here
        List<List<Integer>> results = new ArrayList<>() ;
        if(candidates == null){
          return null ;
        }
        if(candidates.length == 0){
          return results ;
        }
        Arrays.sort(candidates);
        List<Integer> subset = new ArrayList<Integer>() ;
        helper(results , 0 , target , subset , candidates) ;
        return results ;
    }
    public void helper(List<List<Integer>> results , int start , int remintarget , List<Integer> subset , int[] candidates){
         if(remintarget == 0){
           results.add(new ArrayList<Integer>(subset)) ;
           return ;
         }
         for(int i = start ; i < candidates.length ; i++ ){
           if(remintarget < candidates[i]){
             break ;
           }
           if(i >0 && candidates[i] == candidates[i-1]){
             continue ;
           }
           subset.add(candidates[i]);
           helper(results, i , remintarget-candidates[i] , subset , candidates);
           subset.remove(subset.size()-1);
         }

    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值